資源描述:
《linux網(wǎng)絡(luò)編程socket》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在工程資料-天天文庫。
1、網(wǎng)絡(luò)編程的流程:客戶端:1、創(chuàng)建一個socket;2、綁定socket(IP,端口號);因為在connect()中已經(jīng)綁定了,所以不需要用blind()函數(shù)來綁定。serv_addr.sin_family=AF_INET;serv_addr.sin_port=htons(MYPORT);//端口號也就是進程,相當于應(yīng)用程序的編號。端口號要與服務(wù)端的一致,所以綁定的端口號是服務(wù)端的端口號serv_addr.sin_addr.s_addr=inet_addr(IP);//綁定的IP是本機的IP3、發(fā)送建立連接請求con
2、nect();4、收到連接響應(yīng);5、發(fā)送數(shù)據(jù)send();6、關(guān)閉socket,close(sock_fd)。服務(wù)端端:1、創(chuàng)建一個socket;2、綁定socket(IP,端口號),blind();my_addr.sin_family=AF_INET;my_addr.sin_port=htons(MYPORT);//綁定的端口號是自己的端口號my_addr.sin_addr.s_addr=INADDR_ANY;//IP是客戶端任意一個IP3、偵聽來自客戶端的連接請求,listen();4、有客戶端連接請求,為建立
3、請求的客戶端創(chuàng)建一個socket,返回連接響應(yīng),accept();5、接受客戶端發(fā)送的數(shù)據(jù),recv();6、關(guān)閉,close(new_fd)。#include#include#include#include#include#include#include#include#defineMYPORT3999//listeningport#
4、defineBACKLOG10//maxconnectrequests#defineMAXDATASIZE100/*maxdatavolume*/#defineIP"127.0.0.1"main(intargc,char*argv[]){intsock_fd,numbytes;//char*buf;//buf=(char*)malloc(20);charbuf[20];structhostent*host;structsockaddr_inserv_addr;/*socket*/if((sock_fd=socket
5、(AF_INET,SOCK_STREAM,0))==-1){perror("socketcreaterror");exit(1);}serv_addr.sin_family=AF_INET;serv_addr.sin_port=htons(MYPORT);//serv_addr.sin_addr=inet_addr(IP);serv_addr.sin_addr.s_addr=inet_addr(IP);bzero(&(serv_addr.sin_zero),8);/*connect*/if(connect(sock
6、_fd,(structsockaddr*)&serv_addr,sizeof(structsockaddr))==-1){perror("connecterror");exit(1);}printf("Pleaseenterthestring:");gets(buf);/*send*/if((numbytes=send(sock_fd,buf,strlen(buf),0))==-1){perror("senderror");exit(1);}printf("send:%d",numbytes);close(
7、sock_fd);exit(0);}#include#include#include#include#include#include#include#include#defineMYPORT3999//listeningport#defineBACKLOG10//maxconnectrequests#defineMAXDATASIZE1
8、00/*maxdatavolume*/main(){intsock_fd,new_fd,numbytes;/*sock_fd:listeningsocket;new_fd:datasocket*/structsockaddr_inmy_addr;/*serveraddress*/structsockaddr_intheir_addr;/*clientaddr