管理员
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发
楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:
+ `5 T, A* \+ [5 `#include <sys/types.h>
4 h6 ~+ i" _1 ~7 |/ j; T2 ]% ~9 O#include <sys/socket.h>
# O( V; N; A& m3 A0 i/ ]#include <unistd.h> ) Z1 n. [2 d$ S' i1 B( X
#include <netinet/in.h> # ~* {1 J/ V% y2 V- K" a6 W
#include <arpa/inet.h> , f4 h- Z7 q% g8 L/ m
#include <string.h>
( `0 ?8 _+ Z' s5 m#include <stdio.h> - j/ U# v7 V- k& Q
int main() {, B6 T0 C$ n, [
int sockClient;6 o. d1 I$ d) ~& @0 K! F4 k( ]5 u
struct sockaddr_in addrSrv;
2 U$ d3 \9 O- N6 v" y( S& p' |) ~ sockClient = socket(AF_INET,SOCK_DGRAM,0);. [4 h0 L5 L2 P5 B$ R& L/ Q0 o' e4 l
addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");
( d5 }' a2 @$ T" h) K+ O addrSrv.sin_family=AF_INET; Z: g3 r T5 r0 ]
addrSrv.sin_port=htons(6000);
) p: p8 h a2 c7 i4 O# ^ while(1)
* ~6 X$ c. C$ d; q {
; Z ^9 J1 T" B( a1 E7 H7 Y sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr)); h: {& Y- y9 h8 ~3 r
sleep(2);
: e6 w/ ^8 x3 G: i$ \# R }
8 J5 C# B# \, |- c( J close(sockClient);
9 n+ u) z6 V$ @; U( u9 U( | return 0; 0 b% W5 S) U9 A3 l1 q
}
" `0 g/ s ]+ ~: X+ ]! z3 Z4 _- @& q @2 I: i" Y% n0 z
2 V3 m4 D/ d+ c+ B0 u客户端:- #include <stdio.h> 7 s2 S& N+ S3 [ B- B
- #include <sys/types.h>
2 I8 k6 d4 I r% W - #include <sys/socket.h> 5 u* S: X: L' O& Q! E) B' C3 M, z
- #include <netinet/in.h> ' Y' h: n4 O5 D. C# {( m) X+ M q- n
- #include <arpa/inet.h> 6 O( u: o/ r \2 D2 |/ ?& R
- #include <string.h> ; [; E, N1 Q2 H& c
- #include <unistd.h> + x2 Q( x$ |% Y: g6 ?+ m
- #include <fcntl.h> * R5 o! d" W' R! Y5 B$ \
- #include <sys/time.h>
% C9 U: b9 k$ m0 F5 f L( z - #include <sys/select.h> 6 _+ F+ O- t: c, H4 N9 V7 x
- #include <sys/ioctl.h> 2 B' i/ y' p% C5 C6 |2 Y
- int main() {3 ~0 X. p4 K# J0 v, c0 e
- int sockSrv;4 D, p" V0 S% I
- struct sockaddr_in addrSrv;: n+ Q4 d. `9 C) F& R
- int len;
6 n& x* \& h* u) z6 n+ S: i8 _ - char recvBuf[100];
0 C7 B4 E5 m4 A: E+ |+ p8 r9 | - scanf("%s",recvBuf);
" w9 D: V: f, F5 z% r: H - struct sockaddr_in addrClient;. p* v9 D! v- v4 c$ k6 j
- sockSrv = socket(AF_INET,SOCK_DGRAM,0);& \; d( y" O6 G5 U7 R Q
- addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);
9 h/ {+ c3 c7 A K - addrSrv.sin_family = AF_INET;
, _+ K& A' W- r/ U4 h$ n+ z - addrSrv.sin_port = htons(6000);
% V4 K$ ~% U9 x$ y4 p - bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));/ |+ x- |8 T. ]# K9 v# F( n) \
- len = sizeof(struct sockaddr);
. y2 p' Y) n3 Y, o- z) t) n - memset(recvBuf, 0, 100);
9 ~/ b; _3 t$ r, X2 |2 T - recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);: F* @) G8 b4 G. z w
- printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));
5 F" |7 _1 B1 N! I1 G - printf("Client data is:%s\n",recvBuf);, @$ o/ k# N+ C0 A4 w: r; D
- close(sockSrv);! }/ K' i* b! h u7 E8 |/ A
- return 0;
; @+ B% D* b4 L+ A1 L - }
复制代码 ) q. T+ K& j2 j
$ y G, }9 a) z( r
1 a& y0 O) }6 f# a, N: r" C! E4 C( ?+ k/ |' H8 c
|
|