Linux 网络编程六(socket通信UDP版)
//udp接收消息 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int main(int arg, char * args[]) { if (arg < 3) { printf("please print two param!\n"); return -1; } int port = atoi(args[2]); //create socket int st = socket(AF_INET, SOCK_DGRAM, 0); if (st == -1) { printf("create socket failed ! error message :%s\n", strerror(errno)); return -1; } //UDP广播必须设置socket属性 /* int on = 1; if (setsockopt(st, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) == -1) { printf("setsockopt failed ! error message :%s\n", strerror(errno)); return -1; } */ struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); //设置结构sockaddr_in类型是TCP/IP addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = inet_addr(args[1]); char buf[1024] = { 0 }; while (1) { //read read(STDIN_FILENO, buf, sizeof(buf)); if (sendto(st, buf, strlen(buf), 0, (struct sockaddr *) &addr, sizeof(addr)) == -1) { printf("sendto failed ! error message :%s\n", strerror(errno)); break; } memset(buf,0,sizeof(buf)); } close(st); return 0; }
//udp接收消息 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int main(int arg, char * args[]) { if(arg<2) { printf("please print one param !\n"); return -1; } int st=socket(AF_INET,SOCK_DGRAM,0); if(st==-1) { printf("open socket failed ! error message : %s\n",strerror(errno)); return -1; } int port=atoi(args[1]); //defien ip address strcut struct sockaddr_in addr; //define addr type addr.sin_family=AF_INET; addr.sin_port=htons(port); addr.sin_addr.s_addr=htonl(INADDR_ANY); //bind port if(bind(st,(struct sockaddr *)&addr,sizeof(addr))==-1) { printf("bind IP failed ! error message : %s\n",strerror(errno)); goto END; } char buf[1024]={0}; struct sockaddr_in client_addr; socklen_t addrlen=sizeof(client_addr); while(1) { memset(&client_addr,0,sizeof(client_addr)); if(recvfrom(st,buf,sizeof(buf),0,(struct sockaddr *)&client_addr,&addrlen)==-1) { printf("recvfrom failed ! error message : %s\n",strerror(errno)); goto END; }else { printf("from %s:%s",inet_ntoa(client_addr.sin_addr),buf); } memset(buf,0,sizeof(buf)); } END:close(st); return 0; }
.SUFFIXES:.c .o CC=gcc SRCS1=udpsend.c SRCS2=udprecv.c OBJS1=$(SRCS1:.c=.o) OBJS2=$(SRCS2:.c=.o) EXEC1=msend EXEC2=mrecv start:$(OBJS1) $(OBJS2) $(CC) -o $(EXEC1) $(OBJS1) $(CC) -o $(EXEC2) $(OBJS2) @echo "-------ok-----------" .c.o: $(CC) -Wall -g -o $@ -c $< clean: rm -f $(OBJS1) rm -f $(EXEC1) rm -f $(OBJS2) rm -f $(EXEC2)