#include<stdio.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<pthread.h>
#include<strings.h>
int main()
{
int sockfd = socket(AF_INET,SOCK_DGRAM,0); //创建udp套接字socket得到socketfd
struct sockaddr_in ser_addr;
memset(&ser_addr,0,sizeof(ser_addr));
ser_addr.sin_family = AF_INET;
ser_addr.sin_port = htons(21); //这里需要绑定的是本地的ip跟端口,而不是客户端
ser_addr.sin_addr.s_addr = inet_addr("192.168.1.109");
int b = bind(sockfd,(struct sockaddr*)&ser_addr,sizeof(struct sockaddr_in));
if(b == -1)
{ //判断是否绑定成功
perror("bind() error!\n");
}
struct sockaddr_in cli_addr;
int s = sizeof(struct sockaddr);
char buf[20];
char send[]={"over,over"};
int ret;
while(1) //收发数据
{
bzero(buf,20);
ret = recvfrom(sockfd,buf,20,0,(struct sockaddr *)&cli_addr,&s);
if(ret < 0)
{
perror("send() error!\n");
}
printf("%s\n",buf);
sendto(sockfd,send,strlen(send),0,(struct sockaddr *)&cli_addr,s);
}
close(sockfd); //关闭套接字socketfd
}
|