管理员
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发
楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:
0 p5 }/ h2 i$ e7 h F#include <sys/types.h>
7 i; `7 ?* o3 o7 Y5 u# L#include <sys/socket.h> 1 d% B: H$ n) B/ n- `+ I3 U4 o
#include <unistd.h>
7 W( a2 _/ G' E* d" D#include <netinet/in.h> & f T0 b3 a1 `' `; }2 l
#include <arpa/inet.h> ; n& T5 M6 G/ _: X) T
#include <string.h> 9 x" j# g' M L
#include <stdio.h> T# M$ v# c( _7 u- [ {1 e) a
int main() {. r& d, g9 f* \8 h
int sockClient;
, o! i& A' F) a: ~/ z; t& `% t1 S struct sockaddr_in addrSrv;% x+ d: b& j. y0 U7 ^2 h
sockClient = socket(AF_INET,SOCK_DGRAM,0);+ _2 j. p8 N+ h# J% m
addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1"); M' J2 S2 R+ r. I' i
addrSrv.sin_family=AF_INET;
# h6 M1 |2 S. E7 X# N' _ addrSrv.sin_port=htons(6000);/ j( b, r$ g5 S
while(1)
1 p# N7 P! S* @% M- C$ c1 l$ ` {
& `- \) i5 H$ u; R$ j sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));$ r. I- \* @0 ~/ D/ ~8 Y, Z' W
sleep(2);2 J3 d( t* T; e+ M, Z) u
} 9 `- B9 X- s& E- U9 L6 y6 C5 I
close(sockClient); , D; X+ K, Z; \* W
return 0; 3 O1 H" L) j2 d% ~5 O, T
}5 z6 [1 G {9 k& G+ ~ y. F
7 n1 K0 g6 Q, H- q0 w! V+ _& B$ ~+ w0 k
4 d0 K/ M9 C$ Q" z: p' F; T
客户端:- #include <stdio.h>
. Q# @8 |9 l1 J: M - #include <sys/types.h>
1 z) C8 H/ T: x8 E - #include <sys/socket.h>
! B) p/ p. j6 h. l: S - #include <netinet/in.h>
7 o2 N1 _% J% h {( J# M/ B - #include <arpa/inet.h>
' \! F, W4 n/ X, _6 p( V - #include <string.h> : E; x$ K7 P/ g t6 f) u! U
- #include <unistd.h>
+ e/ J% h4 m' _- R: b* Q9 P# M - #include <fcntl.h> 0 s4 p7 U$ a' k4 i0 t( E: S
- #include <sys/time.h> / p7 ]% f. d, Z, P0 T' _) }
- #include <sys/select.h>
9 g. e2 u7 h i4 ^ J9 h - #include <sys/ioctl.h> ; A7 v$ P0 c; P2 ^5 Y( R7 z* R8 j$ X4 t, Z
- int main() {, ^. B% H$ s" }# d' v0 f
- int sockSrv;
" n) E0 W$ c8 l6 D7 W' T% _, Y - struct sockaddr_in addrSrv;
7 I, i- f; C/ z* P0 l - int len;
+ T/ S$ x6 Z" x: t5 v+ M - char recvBuf[100];! }; e- l V$ c) B: K
- scanf("%s",recvBuf);
, s: M2 t1 ~3 K; }6 Q: I( ` - struct sockaddr_in addrClient;
4 b i- k! [% l: ` - sockSrv = socket(AF_INET,SOCK_DGRAM,0);2 c R7 U7 m1 \4 ?3 ~' \
- addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);
' O3 `' |+ U4 S' {+ t - addrSrv.sin_family = AF_INET;
6 E- S G2 |( s1 N* y - addrSrv.sin_port = htons(6000);
4 R" G% I, B8 n3 E! D0 ]" p - bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));' g& H& d3 N+ j. i, h
- len = sizeof(struct sockaddr);( G$ S" {# g, ]9 u
- memset(recvBuf, 0, 100);+ g/ Z/ x- f9 X* q t. b8 ? N
- recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);
0 p5 M" v) O7 f4 Y9 J - printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));
5 v q& w. t9 I( q. T - printf("Client data is:%s\n",recvBuf);
7 I; r1 l5 }6 C; V' S' k - close(sockSrv);7 Z) S- {" E1 S F3 H
- return 0;! T5 ]1 B, W" L. }- w* {
- }
复制代码 ( j5 z; d8 j; Q, ?
W/ X1 Y) U- X& V& w: ` K0 p. v u" i0 Z4 H
% g! e G# u: Y+ {
|
|