管理员
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发
楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端: M% k5 ^# L4 a* G8 Y4 S& c
#include <sys/types.h> + j5 j* ~3 D5 h) g [9 @
#include <sys/socket.h>
/ y& v# o5 T P. m) W#include <unistd.h>
# a e" i- z9 _* O+ u#include <netinet/in.h> 0 _ X9 S" _, s0 g* N0 t8 A- Z+ @" B
#include <arpa/inet.h>
/ ?* o0 r/ P9 D6 a3 B1 M* @; C/ {! R#include <string.h>
9 f. t7 r& u+ Y4 l$ j1 O#include <stdio.h> ' s$ @4 T2 @6 ?6 `# b3 u
int main() {% Y5 s a7 R; Z1 z. e
int sockClient;* A* A8 W) e J* ]+ N: S; a9 D7 a
struct sockaddr_in addrSrv;; b* ~2 q! I# e1 F$ L9 h9 I7 c, X
sockClient = socket(AF_INET,SOCK_DGRAM,0);9 b) R/ I( B1 ?5 f$ U# c9 E
addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");
- a; H V! r% _5 ?) f/ h6 Z& } addrSrv.sin_family=AF_INET;( ]& y d X( |: y& j
addrSrv.sin_port=htons(6000);
2 u2 L! J: b: e% @ while(1)
9 R1 }1 k$ K. ] {1 N- D) {+ |1 D, u" [' W
sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));% e0 h8 U' ]1 L' S! Y- n+ c; N5 N
sleep(2);
. j0 ~7 T2 s" ?- E } $ b$ ?9 Y$ z0 T) J' |' N$ m3 D
close(sockClient); # F8 n+ e& j ?( v
return 0; + l* D% r8 ^9 t% o
}7 R+ ~" E7 _1 V% R
& k$ q. v7 Q8 L0 \9 p" u5 N8 L4 r
% ], H% ]1 \# S
客户端:- #include <stdio.h>
. W3 {( r2 T; R3 n) ~2 f- `9 K - #include <sys/types.h>
% ?) d+ A% Z/ _& D& n8 z Y - #include <sys/socket.h>
( v& I) [# W& X; N. @+ V5 o- c - #include <netinet/in.h> " G) l9 v8 e. c" c3 W9 b
- #include <arpa/inet.h>
B N* T% H! b: l9 N& X1 i* H - #include <string.h> ( S* R: ]6 W% M& o) L' l) z& M
- #include <unistd.h> ! J! ~* ?" ^0 Y
- #include <fcntl.h> # @8 J' O' e0 M! T
- #include <sys/time.h>
7 ]& R8 h4 h' f! t1 s& k - #include <sys/select.h>
* q7 p! P" p4 b! P" z' d5 G - #include <sys/ioctl.h> $ P6 o- m+ n2 @7 w
- int main() {' _7 P3 l" A! N; g# f3 M a
- int sockSrv;5 t x2 c. ^0 j7 P
- struct sockaddr_in addrSrv;
2 U4 N; v' S5 q5 s, C - int len;
4 e0 L3 m0 m1 J6 a! e/ j - char recvBuf[100];
3 U$ H( @" {9 }1 |' y( v7 T5 m) ?# F - scanf("%s",recvBuf);2 A3 d3 l( }8 o4 H' L
- struct sockaddr_in addrClient;9 p) X2 \' j6 C9 S) J! T
- sockSrv = socket(AF_INET,SOCK_DGRAM,0);
I, x* m* R- v1 |% V0 [ - addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);* ~8 V( \# g: ^9 ~" A
- addrSrv.sin_family = AF_INET;
, m0 r) x/ N: A ?# |. G - addrSrv.sin_port = htons(6000);( e! c# q! G) C! O
- bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));
4 P0 u0 Z. K5 s9 O& o( H - len = sizeof(struct sockaddr);. I. r. y" t0 N' p; p1 f/ i
- memset(recvBuf, 0, 100);
! k/ E9 I+ \! |: i1 _! G8 i - recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);
& [" A3 i. u8 F9 c8 _1 L* r - printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));
& { C& T* X7 [$ b/ w8 J' ` - printf("Client data is:%s\n",recvBuf);
R' \. k+ n( [: r( _ - close(sockSrv);
! ?- o! c9 d) J( o4 m# e4 i$ v. i - return 0;
$ d& v6 D) O+ k E' Q- R+ k - }
复制代码
! Z/ h6 H, w2 F* H: p1 N
4 z$ d' R _" o. `( L
0 H) y3 n+ q) a
& f" S {- S: K: B( e% Z+ {! o+ K2 d |
|