Linux下C語言實現UDP Socket程式設計

2021-09-23 23:35:45 字數 2987 閱讀 3014

該博文參考了linux c socket 程式設計之udp一文,在這裡表示感謝!

傳送方:

/* 

* file: udp_sender.c

* author: henry

* * created on 2023年5月29日17:08:13

* * 主要實現:傳送20個文字訊息,然後再傳送乙個終止訊息

*/#include

#include

#include

#include

#include

#include

#include

intpower

(int base,

int exp)

;int

str_to_num

(const

char

*s);

intmain

(int argc,

char

** ar**)

int socket_descriptor;

//套介面描述字

int iter=0;

char buf[80]

;struct sockaddr_in address;

//處理網路通訊的位址

bzero

(&address,

sizeof

(address));

address.sin_family=af_inet;

"192.168.2.1");//這裡不一樣

address.sin_addr.s_addr=

inet_addr

(ar**[1]

);//這裡不一樣

address.sin_port=

htons

(str_to_num

(ar**[2]

));//建立乙個 udp socket

socket_descriptor=

socket

(af_inet,sock_dgram,0)

;//ipv4 sock_dgram 資料報套接字(udp協議)

for(iter=

0;iter<=

20;iter++

)sprintf

(buf,

"stop\n");

sendto

(socket_descriptor,buf,

sizeof

(buf),0

,(struct sockaddr *

)&address,

sizeof

(address));

//傳送stop 命令

close

(socket_descriptor)

;printf

("messages sent,terminating\n");

exit(0

);return

(exit_success);}

intstr_to_num

(const

char

* s)

return n;

}int

power

(int base,

int exp)

接收方:

/* 

* file: udp_receiver.c

* author: henry

* * created on 2023年5月29日17:09:11

* * 主要實現:傳送20個文字訊息,然後再傳送乙個終止訊息

*/#include

#include

#include

#include

#include

#include

#include

intpower

(int base,

int exp)

;int

str_to_num

(const

char

*s);

intmain

(int argc,

char

** ar**)

int sin_len;

char message[

256]

;int socket_descriptor;

struct sockaddr_in sin;

printf

("waiting for data from sender \n");

bzero

(&sin,

sizeof

(sin));

sin.sin_family=af_inet;

sin.sin_addr.s_addr=

htonl

(inaddr_any)

; sin.sin_port=

htons

(str_to_num

(ar**[1]

)); sin_len=

sizeof

(sin);

socket_descriptor=

socket

(af_inet,sock_dgram,0)

;bind

(socket_descriptor,

(struct sockaddr *

)&sin,

sizeof

(sin));

while(1

)}close

(socket_descriptor)

;exit(0

);return

(exit_success);}

intstr_to_num

(const

char

* s)

return n;

}int

power

(int base,

int exp)

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語言實現簡單Shell

include include include include include include include include define max string 256 define signin define signout define signpine const char expst ex...

linux下ping的C語言實現

include stdio.h include signal.h include arpa inet.h include sys types.h include sys socket.h include unistd.h include netinet in h include netinet ip...