日期:2014-05-16 浏览次数:20767 次
#include<stdio.h> #include<netinet/in.h> #include<arpa/inet.h> #include<unistd.h> #include<fcntl.h> #include<sys/stat.h> #include<sys/types.h> #include<sys/socket.h> #define REMOTEPORT 4567 #define REMOTEIP "127.0.0.1" void main() { int s,len; struct sockaddr_in addr; int addr_len; char msg[256]; int i=0; if((s=socket(AF_INET,SOCK_DGRAM,0))<0) { perror("error"); exit(1); } else { printf("socket created .\n"); printf("socked id:%d\n",s); printf("remote ip:%s\n",REMOTEIP); printf("remote port:%d\n",REMOTEPORT); } len=sizeof(struct sockaddr_in); bzero(&addr,sizeof(addr)); addr.sin_family=AF_INET; addr.sin_port=htons(REMOTEPORT); addr.sin_addr.s_addr=inet_addr(REMOTEIP); while(1) { bzero(msg,sizeof(msg)); len=read(STDIN_FILENO,msg,sizeof(msg)); sendto(s,msg,len,0,&addr,&addr_len); printf("\nInput message: %s",msg); len=recvfrom(s,msg,sizeof(msg),0,&addr,&addr_len); printf("%d:",i); i++; printf("Received message :%s",msg); } }
#include<stdio.h> #include<netinet/in.h> #include<arpa/inet.h> #include<unistd.h> #include<sys/types.h> #include<sys/socket.h> #define LOCALPORT 4567 void main() { int mysock,len; struct sockaddr_in addr; int i=0; char msg[256]; int addr_len; if((mysock=socket(AF_INET,SOCK_DGRAM,0))<0) { perror("error"); exit(1); } else { printf("socket created .\n"); printf("socked id :%d\n",mysock); } addr_len=sizeof(struct sockaddr_in); bzero(&addr,sizeof(addr)); addr.sin_family=AF_INET; addr.sin_port=htons(LOCALPORT); addr.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(mysock,&addr,sizeof(addr))<0) { perror("connect"); exit(1); } else { printf("bind ok.\n"); printf("local port :%d\n",LOCALPORT); } while(1) { bzero(msg,sizeof(msg)); len=recvfrom(mysock,msg,sizeof(msg),0,&addr,&addr_len); printf("%d: ",i++); printf("message from :%s\n",inet_ntoa(addr.sin_addr)); printf("message length : %d\n",len); printf("message:%s\n\n",msg); sendto(mysock,msg,len,0,&addr,addr_len); } }