用c語言實現udp 通訊。寫乙個udp 的客戶端,可以向外傳送訊息。再寫乙個udp服務端,接收客戶端的訊息,並且列印出來。
*事先說明:
在window和linux中有一下結構:
struct sockaddr
struct sockaddr_in //在netinet/in.h 中定義:儲存ip位址,使用in_addr這個資料結構
typedef uint32_t, in_addr_t;
struct in_addr
* 伺服器**如下:
#include
#include
#include // for close()
#include
#include
#include
#include
#include
#define port 12347
#define maxdatasize 1024
int main()
bzero(&server, sizeof(server));//將位元組型別的字串的前n個位元組為零,包括'\0'
server.sin_family = af_inet;
server.sin_port = htons(port);
server.sin_addr.s_addr = htonl(inaddr_any);
if(bind(sockefd, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -1)
sin_size = sizeof(struct sockaddr_in);
while(1)
recemsg[num] = '\0';
printf("you got a message (%s) from %s\n", recemsg, inet_ntoa(client.sin_addr));
if(strcmp(recemsg, condition) == 0)
for(i=0; i1-i];
}sendmsg[i] = '\0';
sendto(sockefd, sendmsg, strlen(sendmsg), 0 ,(struct sockaddr *)&client,sin_size);
}close(sockefd);
return
0;}
下面是客戶端的**:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define server_ip "127.10.10.11"
#define port 12347
#define maxdatasize 1024
int main()
bzero(&server, sizeof(server));
server.sin_family = af_inet;
server.sin_port = htons(port);
server.sin_addr.s_addr = inet_addr(server_ip);
socklen_t len;
len = sizeof(struct sockaddr_in);
while(1)
recvbuff[numbytes] = '\0';
printf("server return message is %s\n", recvbuff);
}close(fd);
return
0;}
這裡客戶端還有另一種寫法,就是在啟動客戶端的**時要手動傳入ip的引數:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define server_ip "127.10.10.11"
#define port 12347
#define maxdatasize 1024
int main(int argc, char
const *argv)
bzero(&server, sizeof(server));
server.sin_family = af_inet;
server.sin_port = htons(port);
server.sin_addr = *((struct in_addr *)he->h_addr);
socklen_t len;
len = sizeof(struct sockaddr_in);
while(1)
recvbuff[numbytes] = '\0';
printf("server return message is %s\n", recvbuff);
}close(fd);
return
0;}
編譯:gcc client.c -oclient
執行:./client 127.0.0.1
此時的結果和上面的客戶端**的結果一樣。
Linux下C語言實現簡單Shell
include include include include include include include include define max string 256 define signin define signout define signpine const char expst ex...
Linux下C語言實現CopyFile
linux下c語言實現檔案拷貝 function copy file from file1 to file2 how to execute copyfile file1 file2 under linux data 2007 05 09 include fprintf stderr,bufsiz i...
Linux下C語言實現UDP Socket程式設計
該博文參考了linux c socket 程式設計之udp一文,在這裡表示感謝!傳送方 file udp sender.c author henry created on 2019年5月29日17 08 13 主要實現 傳送20個文字訊息,然後再傳送乙個終止訊息 include include in...