管理员
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发
楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:
7 S; Z$ [' P0 K) |8 |#include <sys/types.h>
: x* `7 ^& T! j' v5 |+ X3 r; y#include <sys/socket.h>
0 F' Q. ?) o+ _7 A& o5 A#include <unistd.h> 1 |- J" M$ z: k4 A" X0 l
#include <netinet/in.h>
% {0 L) @: \0 g0 i$ F$ r9 h; I#include <arpa/inet.h>
) h0 a) \2 Y# R3 S' Q5 c1 F) u#include <string.h>
0 q7 m* [- }8 |4 F#include <stdio.h> ) Q$ t6 J' ^7 o# G8 y' v8 D A1 K
int main() {5 O% W( _' B2 b S2 q$ ~4 D7 j' f
int sockClient;
7 ?* }+ }$ ~8 b8 l$ t& K struct sockaddr_in addrSrv;; u; _# B% ~; N8 N; @
sockClient = socket(AF_INET,SOCK_DGRAM,0);
0 \3 r7 l1 F# y! J addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");6 g* e( q6 k. _- Z# ^0 x8 n6 `7 F
addrSrv.sin_family=AF_INET;
7 W2 p7 J) W- \1 M! ` addrSrv.sin_port=htons(6000);
* n0 j8 \. q( u while(1)" |% p4 y% ]1 \# r; n# e
{+ [- l( r. h! \
sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));5 D" l9 E. D* S
sleep(2);
$ ~' X; K% v6 ?& T/ N; ~. ~8 h }
7 U' w6 S# _: o/ I close(sockClient); ' u9 r& E5 j3 a% u9 {, w6 ]- ~
return 0;
6 x) m5 i2 c- t) `9 @0 I}
0 H: `2 ]) T6 \6 G' T( B3 x6 U% x) V1 h
/ g3 @" a9 I( S) V
客户端:- #include <stdio.h> : ]. e* a0 f6 |2 w* }
- #include <sys/types.h>
x( z9 M2 H5 E! P - #include <sys/socket.h> & r: _+ E+ F& M' V/ A2 L, M
- #include <netinet/in.h>
/ D3 T% T- P3 t1 C2 a1 G% s - #include <arpa/inet.h>
8 Y8 g7 r, S. [% b5 U3 | - #include <string.h> 7 q+ S0 b* Z4 ~+ A4 {7 p k$ ~) K
- #include <unistd.h> / e8 ?! {" w5 [+ ` n9 O
- #include <fcntl.h> O' p, e' {0 I
- #include <sys/time.h> ) P, q9 O. o8 @ I+ e
- #include <sys/select.h>
' B' a% _( X/ E- i4 {, Y3 r - #include <sys/ioctl.h> 6 P5 t6 f; G0 X9 U; i
- int main() {
# p3 G% ^+ [' u8 q0 F1 C - int sockSrv;
2 s E8 ^$ i# \3 q9 X7 o9 O" g; R - struct sockaddr_in addrSrv;& x; U8 S2 E- z! H
- int len;
- }, F* ]% i u: e z3 M8 I0 V - char recvBuf[100];
7 e A- x) y6 B" G4 F; ` - scanf("%s",recvBuf);5 Y8 X% y3 K0 N, Q: Q
- struct sockaddr_in addrClient;
& X& l7 q% L e1 ~4 E, V - sockSrv = socket(AF_INET,SOCK_DGRAM,0);
" {0 V8 [* f6 _! U! B# _: b - addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);
+ \9 q. _% x9 n - addrSrv.sin_family = AF_INET;
. ?, G0 V% @; O4 J7 v* E7 ? - addrSrv.sin_port = htons(6000);
1 Q6 |& m9 B* ?& C1 I) P - bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));4 @8 u' Z' d' a7 M" o% I
- len = sizeof(struct sockaddr);4 n3 @* @) O# X/ _' m
- memset(recvBuf, 0, 100);
% E' @) ]9 I& V$ v* T# a - recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);
, F% m7 |, T' i+ c& t, A. g, y - printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));# o( `! G$ ^% P7 g
- printf("Client data is:%s\n",recvBuf); Z; F+ S2 c3 m6 B B9 Y; T
- close(sockSrv);
, |" o, h+ @& o9 l4 X - return 0;; Z7 R, }1 ?2 X9 R" v
- }
复制代码
6 Z8 L, n4 i: g8 E2 `# w1 I" Z! i" q: y
* p: \, T& ]' n+ X {
! Z- t$ I1 X6 q |
|