管理员
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发
楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:( D* v+ e. I% D; t4 N$ d
#include <sys/types.h> 6 _4 X) V2 y# H( R+ F
#include <sys/socket.h> 3 ]5 a. {+ I! R5 f3 o3 b
#include <unistd.h> " h( I# \6 K2 R% r6 V W
#include <netinet/in.h> ' s" o7 m$ h. o
#include <arpa/inet.h>
, s/ P$ F# Y7 W/ N/ v! k7 _/ X#include <string.h> " ]2 h) a# o I9 [
#include <stdio.h>
" @2 V5 C6 P! t" cint main() {& i" |$ A$ n) o0 s7 h2 L
int sockClient;
; m: r% E0 B5 _! M6 h. B struct sockaddr_in addrSrv;: I- _5 J% Y6 T5 n4 y
sockClient = socket(AF_INET,SOCK_DGRAM,0);9 s. i E0 I- X. u
addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");4 _7 a& O* G% E
addrSrv.sin_family=AF_INET;
, z! A! d; `# v addrSrv.sin_port=htons(6000);9 f( M) f$ E% y; S' p
while(1)3 I4 j+ z6 l8 u8 A
{
& T9 T1 |9 Y# Y sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));
1 w9 Y5 n! [! U8 {% B# ^1 C& }! N sleep(2);
# n& c+ Q6 K j4 k } ) K2 I# W: T T
close(sockClient);
8 W% z2 B+ K2 t8 g# ^$ y6 L return 0;
4 [6 c) _* _0 l}/ B; l# ?/ ~; s+ @, f
; H6 G4 Y* q8 w/ T. c3 G' l, {
/ R4 u8 ]" i) U/ I( C, M: X客户端:- #include <stdio.h>
& G c1 X3 N4 K* K: p( f6 g - #include <sys/types.h>
2 m S$ V$ j1 P) B4 Z( I; z: u - #include <sys/socket.h>
5 U! o- ?8 W! S* F- J; o a+ p- [ - #include <netinet/in.h>
' Z/ C4 m$ ?* b) [ - #include <arpa/inet.h> ! I7 \9 Z2 K( E( b# a8 t) T
- #include <string.h>
3 s7 Q5 t" s% \5 n) N# ~: e+ D - #include <unistd.h>
7 G; Z3 d8 z. ~. \5 E - #include <fcntl.h> + d8 _ _ i! M$ k& R0 R: F
- #include <sys/time.h> - i0 F$ ^" e% O. j
- #include <sys/select.h>
1 e$ p v. }; D, }9 l - #include <sys/ioctl.h> 0 S0 A3 ~4 _/ y) @2 z( [
- int main() {
" d9 {) B" L& Q8 H; g; u& h - int sockSrv;
& x1 @5 J! z) |* V, n/ } - struct sockaddr_in addrSrv;' S X! a( W3 e( E: E
- int len;; f, \. K! E# A8 `$ k& q. j* _
- char recvBuf[100];" N2 B/ Z; [2 A1 l6 c$ f& n
- scanf("%s",recvBuf);
8 G: m7 w/ N* P1 K - struct sockaddr_in addrClient;
5 p$ V8 i% Z1 s) g5 @' q b - sockSrv = socket(AF_INET,SOCK_DGRAM,0);
; n. ^: ~" @" m4 [3 b( X - addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);0 @' Y2 v+ C9 G- m1 `6 D
- addrSrv.sin_family = AF_INET;* S" h% |4 T& ?% V
- addrSrv.sin_port = htons(6000);$ ~: } M" W6 ^" Z% f' G- A
- bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));
. k" s5 o; Y$ U/ s! ]5 _4 r% \, x - len = sizeof(struct sockaddr);
. S% ]: d% a: _& q- e - memset(recvBuf, 0, 100);
0 F5 z8 e0 v+ L$ ] - recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);& ?1 `) h7 @% S
- printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));
) I+ p6 p0 ^" I- w/ ?2 m% w - printf("Client data is:%s\n",recvBuf);
% K; |3 K Z! X* J! h1 F7 y - close(sockSrv);
5 z6 ?3 ]. Z; M. x - return 0;1 f" Y" u) G% r% z
- }
复制代码 7 B" t$ I& ^' e
7 u! d S2 ~5 U
$ w0 H8 X R, ]! I3 y
- E, E+ B& Z2 F& q1 n: B |
|