1 .server
deepfuture@deepfuture-laptop:~/private/mytest$ ./testupds
server wait....
server read :deepfuture.iteye.com
server send :hello
server wait....
^C
deepfuture@deepfuture-laptop:~/private/mytest$
2.client
deepfuture@deepfuture-laptop:~/private/mytest$ ./testupdc
client send....
client send :deepfuture.iteye.com
client read :hello
deepfuture@deepfuture-laptop:~/private/mytest$
3.source
1)server
#include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> //deepfuture.iteye.com int main(void){ int fd; int addresslen; struct sockaddr_in address;//地址信息结构 int rc; //建立socket fd=socket(AF_INET,SOCK_DGRAM,0);//fd为socket if (fd==-1){//错误,类型从errno获得 perror("error");//perror先输出参数,后跟":"加空格,然后是errno值对应的错误信息(不是错误代码),最后是一个换行符。 } //bind 到socket fd address.sin_family=AF_INET;//IPV4协议,AF_INET6是IPV6 address.sin_addr.s_addr=htonl(INADDR_ANY);//l表示32位,htonl能保证在不同CPU的相同字节序 address.sin_port=htons(1253);//端口号,s表示16位 addresslen=sizeof(address); bind(fd,(struct sockaddr *)&address,addresslen);//bind while(1){ struct sockaddr_in clientaddress; int address_len; char mybuf[100]; char *buf="hello\n"; int n; printf("server wait....\n"); fflush(stdout); address_len=sizeof(clientaddress); n=recvfrom(fd,mybuf,100,0,(struct sockaddr *)&clientaddress,&address_len);//读数据 printf("server read :%s\n",mybuf); sendto(fd,buf,strlen(buf)+1,0,(struct sockaddr *)&clientaddress,address_len);//写数据 printf("server send :%s\n",buf); } }
2)client
#include <stdio.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> //deepfuture.iteye.com int main(void){ int fd; int addresslen; struct sockaddr_in address;//地址信息结构 int rc; char mybuf[100]; char *buf="deepfuture.iteye.com\n"; int n; //建立socket fd=socket(AF_INET,SOCK_DGRAM,0);//fd为socket if (fd==-1){//错误,类型从errno获得 perror("error");//perror先输出参数,后跟":"加空格,然后是errno值对应的错误信息(不是错误代码),最后是一个换行符。 } //bind 到socket fd address.sin_family=AF_INET;//IPV4协议,AF_INET6是IPV6 address.sin_addr.s_addr=htonl(INADDR_ANY);//l表示32位,htonl能保证在不同CPU的相同字节序 address.sin_port=htons(1253);//端口号,s表示16位 addresslen=sizeof(address); printf("client send....\n"); fflush(stdout); sendto(fd,buf,strlen(buf)+1,0,(struct sockaddr *)&address,addresslen);//写数据 printf("client send :%s\n",buf); n=recvfrom(fd,mybuf,100,0,NULL,NULL);//读数据 printf("client read :%s\n",mybuf); }