管理员
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发
楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:
/ f' X& C8 R8 y1 @& a#include <sys/types.h> . v+ b8 u! d$ p! h1 N0 m* H- w
#include <sys/socket.h> 3 n* a) M* j6 n! u5 K5 T
#include <unistd.h>
# \0 p/ v/ T8 V; B! U#include <netinet/in.h> 6 S" t/ |# h( z4 ]! d3 @# ]
#include <arpa/inet.h>
. i, N& L8 e1 }4 c& U9 J% x#include <string.h>
8 Y" o' V# d7 u; W#include <stdio.h>
& s0 S- s% o! Y2 C, Aint main() {
1 j4 u# P5 x) T int sockClient;
, y7 e/ f4 n+ O struct sockaddr_in addrSrv;
5 W7 E6 A* T& [% V# d' [; D sockClient = socket(AF_INET,SOCK_DGRAM,0);- @/ U0 F; d2 E
addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");
$ `. O) J9 }. s5 ~/ j addrSrv.sin_family=AF_INET;
, c% T; n/ _. t9 J: H0 \ addrSrv.sin_port=htons(6000);
8 u2 o% M! Y( {0 @4 L while(1)
& x6 W8 q1 b2 P/ ~+ x { u3 q7 l- q" `) ?4 {
sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));$ j5 `: y9 ^% R; o: K2 @/ d
sleep(2);& F5 S' L8 A, M5 Y" I) ^
}
& h5 y0 `2 S' m6 L, E close(sockClient); ! O# F7 Q6 r6 z7 v, F: d* o
return 0; 2 r R3 K0 s) m$ N7 H9 u
}
/ w2 X/ }* f, q5 i2 N3 }* ^# o, O" e( K" ~$ f
' _: f/ l9 G, w6 Q9 {6 [$ }/ b
客户端:- #include <stdio.h> : `3 K8 u5 X1 Y' {( h
- #include <sys/types.h>
: F3 @+ k$ M0 m - #include <sys/socket.h> % {; c8 f3 E# m8 g2 }
- #include <netinet/in.h> 8 U4 |7 }2 x$ @
- #include <arpa/inet.h> ) E$ Y9 D; c. b8 T% r- M
- #include <string.h> 4 t) A; [3 o) s7 |. B
- #include <unistd.h> . {; E" {. |, b# P$ N/ q) ]8 y
- #include <fcntl.h> 3 z9 @" @+ J6 G5 p+ A6 \5 }
- #include <sys/time.h> % F) ^/ `; n0 p# v+ J
- #include <sys/select.h> , y6 A6 M7 W' T2 P- g
- #include <sys/ioctl.h>
% F" c, k' x4 s% S' m - int main() {
: B" z! x8 d! v" v3 x - int sockSrv;/ h! e* {) E2 Y- D( t
- struct sockaddr_in addrSrv;
; [4 U1 D( S- I9 s r - int len;$ K) M6 z5 f2 \) _: W
- char recvBuf[100];
. H5 j4 k' k ?2 ^ - scanf("%s",recvBuf);
& C2 }, o3 k/ V6 C4 z, s - struct sockaddr_in addrClient;. C7 }" u- a2 x8 q7 \
- sockSrv = socket(AF_INET,SOCK_DGRAM,0);
+ @# X; ^, _* l% X- N- \- w - addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);/ u6 Z, l! [. V3 N8 t0 `% F
- addrSrv.sin_family = AF_INET;
7 P2 I7 R9 R' H - addrSrv.sin_port = htons(6000);* ^- N1 x8 Q' S9 }4 L
- bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));
: Z+ M8 Y9 n2 O4 G( B - len = sizeof(struct sockaddr);
3 l Y' K; _5 |8 Z6 i: n5 Q - memset(recvBuf, 0, 100);
4 w9 l" J* @, B8 C# l - recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);/ w. H+ j: e' l
- printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));
( e7 f0 `* a8 p$ i$ u - printf("Client data is:%s\n",recvBuf);
* R, a0 O. J% e) r c - close(sockSrv);4 d" e0 B N, o9 Z
- return 0;
) n0 E3 ?5 L* K. S$ m% A - }
复制代码 ; T+ I% b& q7 T$ L% Q5 P2 P
4 [: ~, G- J. V/ H
: x; _, E" u9 H0 J1 x, c2 G" C& v( M3 H
|
|