管理员
   
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发

楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:
0 S- s) f4 |& Q j9 t, j#include <sys/types.h>
& O$ Y5 W( H( O: d$ ^#include <sys/socket.h> : h- q: t" B/ O, u/ [: I' l
#include <unistd.h>
) x4 w9 V7 v( W#include <netinet/in.h> . {0 o$ H) N) k2 N
#include <arpa/inet.h> 4 j8 _( x- p4 R
#include <string.h> ; C" E# {" f9 D: t4 C
#include <stdio.h> : w/ K7 N3 m6 E. ?4 u
int main() {2 _) p0 a- j- E$ w7 M
int sockClient;; Z# Y h, t. t1 x2 [
struct sockaddr_in addrSrv;
, N: q) @* K7 x+ ` sockClient = socket(AF_INET,SOCK_DGRAM,0);
: a, R* w- p3 J9 {, \+ v addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");
6 d9 u# [2 ?2 T0 @4 r( { addrSrv.sin_family=AF_INET;
4 e7 l+ R, k4 ~) e3 f3 O addrSrv.sin_port=htons(6000);, D4 k6 _, K+ a3 F/ j7 [0 Z) O
while(1)
& |4 V* E& x% S# l- {/ C {
# X- `: Q' x4 j% | sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));
# {1 U8 L3 _( ?- m) A sleep(2);. [( l3 \: V3 D& B- g
}
1 L, R( `- y# C4 \5 }" P& Y! F7 h close(sockClient); + U2 A# M: I$ Y' x9 c% w
return 0;
3 m, b' w2 B- D: ]}3 Z. b* p3 p$ ~ ~0 g8 ]6 U1 \
R, V0 H& K5 b" W: M0 u: S4 L* T6 l4 e& c' N
客户端:- #include <stdio.h> S" z" E5 R* c/ {/ `( j# p% D ^- d
- #include <sys/types.h> W' }- n* J4 X# ^9 ~3 x
- #include <sys/socket.h>
( L, K% e$ z$ L7 b3 d( I - #include <netinet/in.h> * \& s$ o& R H4 Q+ E, L7 Z9 [( w
- #include <arpa/inet.h> : d" G9 l% t, `
- #include <string.h> ' K8 {) ^9 R7 z$ X; d- D
- #include <unistd.h>
?) O @, x9 M* G- T - #include <fcntl.h>
, O; y+ K3 l) e7 m# | - #include <sys/time.h>
& s1 }2 n' d0 G6 [0 y - #include <sys/select.h> 0 G1 r! Q+ M3 ]4 p$ `
- #include <sys/ioctl.h> 6 G: i& m9 J; I+ M& g* t
- int main() {1 N5 T1 G' }8 ^8 `
- int sockSrv;7 H, I/ \" K3 A
- struct sockaddr_in addrSrv;8 n9 {/ G9 `3 \( t; R% b
- int len;
" W% y6 r( w+ X2 d" K* D# B% c - char recvBuf[100];
) U( Z8 h" u B" F+ S - scanf("%s",recvBuf);8 V- Q& O, _" ?3 C# m
- struct sockaddr_in addrClient; b: y5 D; f6 W- P4 N, X. @- ]
- sockSrv = socket(AF_INET,SOCK_DGRAM,0);
- E$ @3 J; s- w1 e, h - addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);
& N6 A; _! i6 e0 g2 z8 m/ c* \ - addrSrv.sin_family = AF_INET;
q4 `/ @' x! i. Z7 R2 t4 { - addrSrv.sin_port = htons(6000);
( m* ^: S$ | h; P- R. J$ _9 B - bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));
3 c+ l' h0 b- E" i% s5 d4 u - len = sizeof(struct sockaddr);
5 x, |8 ^. P! @" c0 C6 W7 t - memset(recvBuf, 0, 100);& ]7 p: N1 Q0 ^* M+ w* ~- l: p1 J( r
- recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);1 @; v7 r# i4 M8 r! q3 b& X
- printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));3 D& l( r, [3 ?6 [8 e+ ]+ H- e. z
- printf("Client data is:%s\n",recvBuf);. y0 l" S" ?4 }6 E- D( ~1 z% M
- close(sockSrv);: F q# K1 h: C. @/ F! p9 d. d
- return 0;, f: e; V, }# I$ {' u
- }
复制代码
# Y; K$ e( K% P( ?/ l2 j1 E* z! @. S8 a5 }3 l" h8 I& R( h
# a- S8 \4 h9 t" ]; P. y
6 \+ @' h( \% E& x2 }- m. n) T( e$ x+ a
|
|