本文參考自 21天學通linux c編程
socket編程可參考:
socket編程:
http://www.cnblogs.com/skynet/archive/2010/12/12/1903949.html
http://www.kuqin.com/networkprog/20080512/8361.html
網路位元組順序以及轉換函式
http://blog.sina.com.cn/s/blog_4ad7c25401019qqb.html
1,設定通訊端
2,讀取通訊端狀態
3,UDP用戶端實現
4,UDP伺服器實現
1,設定通訊端
2,讀取通訊端狀態
#include<sys/types.h>#include<sys/socket.h>#include<stdio.h>int main(){ int s; int val=1,len,i ; len= sizeof(int); if((s = socket(AF_INET,SOCK_STREAM,0))<0) //creat { perror("connect"); exit(1); } else { printf("a socket was created.\n"); printf("socket number:%d\n",s); } i=setsockopt(s,SOL_SOCKET,SO_TYPE,&val,len); //set if("i==0") { printf("set socket ok.\n."); } else { printf("set socket error.\n."); } getsockopt(100,SOL_SOCKET,SO_TYPE,&val,&len); //get perror("socket");}
3,UDP用戶端實現
有些編譯器報錯則在使用addr時(struct sockaddr *)&addr
#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"int main(int argc,char *argv[]){ 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) //建立一個socket { 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 \n",msg); len= recvfrom (s,msg,sizeof(msg),0,&addr,&addr_len);/*這是接收到的資訊。*/ printf("%d :",i); i++; printf("Received message: %s \n",msg); /*這是伺服器返回的資訊。*/ } }
4,UDP伺服器實現
有些編譯器報錯則在使用addr時(struct sockaddr *)&addr
#include <stdio.h>#include <netinet/in.h>#include <arpa/inet.h>#include <unistd.h>#include <sys/types.h>#include <sys/socket.h>#define LOCALPORT 4567int main(int argc,char *argv[]){ 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); 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); /*以上將字串返回給用戶端*/ } }