管理员
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发
楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:5 M# i3 C% V) }$ A- G i
#include <sys/types.h>
1 |) P! h6 I2 F& W! B( u& \#include <sys/socket.h>
: z# y0 {5 T/ g2 l0 w" n C! n#include <unistd.h>
* N2 G/ X) g) K6 b8 a8 O' ]- f#include <netinet/in.h>
$ ~* l) l* e5 }1 I# S. @#include <arpa/inet.h> + w4 ^4 e5 P& e' L Q- ^! A
#include <string.h> 0 k9 {) B, s6 t2 u, o6 F
#include <stdio.h> ) ~; d2 o0 `' M, i, @5 a
int main() {: c+ j7 c; K5 I! q! L$ j4 X/ o
int sockClient;/ R* b4 r* |4 v1 Z! p W
struct sockaddr_in addrSrv;7 {' \& q, z& ]# P
sockClient = socket(AF_INET,SOCK_DGRAM,0);* c5 A) |7 {- U; w3 b/ _
addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");- W+ u9 d" r" G( y6 ^
addrSrv.sin_family=AF_INET;8 E8 Q# }4 ?3 z' O6 { o1 M1 J
addrSrv.sin_port=htons(6000);9 @9 q; P4 B, ]' D
while(1)
, k& k$ u5 Z& C- c! Q! N {- j2 k( J9 f1 A7 h
sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));
% x* P0 g% e7 { sleep(2);
' e9 e: w$ O( o: J6 l } ' D2 b) J" o4 W6 S
close(sockClient);
* v2 f, c9 |! i return 0; 3 o' e8 K1 K& P s3 s2 m$ K/ v
}) s6 ^' C$ z5 R5 O* X( o& p
3 D7 b) k+ _7 h
0 C$ ^- l; H/ J1 K客户端:- #include <stdio.h>
5 v" b/ c) ]1 K5 F: a" Z - #include <sys/types.h> " q5 Y- ]4 p2 T( @9 V
- #include <sys/socket.h> 3 `* D6 i6 \# I S' Y! S
- #include <netinet/in.h> 1 N3 t% X3 `( S, P, c3 `$ L
- #include <arpa/inet.h>
/ x! T8 b" S; H! C" Y3 P5 G5 F: P - #include <string.h> ' h4 Z1 P j3 M
- #include <unistd.h>
; Q6 s( ^7 h8 q4 S0 j/ ? - #include <fcntl.h> 3 i" } b9 u5 B2 ^
- #include <sys/time.h>
: F, s( h* W) v& I1 [( J1 o1 l% G - #include <sys/select.h>
1 T8 A) Y2 E. }" R- `' h: _% [8 \ - #include <sys/ioctl.h> * {5 X- K3 v/ Y% n
- int main() {+ e4 H: T5 p2 m& g0 U
- int sockSrv;
0 j4 X( o. h% {7 P - struct sockaddr_in addrSrv;
; b: D% i4 Q# F9 q: d1 I1 F - int len;0 u& ~4 k$ F9 ?; Z2 {
- char recvBuf[100];
' i( _+ F8 d% _ - scanf("%s",recvBuf);
: I+ C0 f0 c2 Y* O - struct sockaddr_in addrClient;
7 ]+ k- D+ I! d7 X3 h8 k - sockSrv = socket(AF_INET,SOCK_DGRAM,0);
0 h& \9 ]- R5 v7 o5 S7 c" L' G - addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);
! u# \& f3 G' x% S - addrSrv.sin_family = AF_INET;
( T4 y- A- C! V) m# c: c2 s7 E - addrSrv.sin_port = htons(6000);
3 t3 b# a' G# R+ V! U' G - bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));
5 Z) u9 J- b. s" s4 Y! h9 ] - len = sizeof(struct sockaddr);2 C, N7 ` n/ \# O& F
- memset(recvBuf, 0, 100);3 h6 v* _+ {8 k; g1 W
- recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);* y7 N' n9 Z7 z) R
- printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));9 E- g9 ]& W7 o( ~# n4 ]
- printf("Client data is:%s\n",recvBuf);
! T* }' D7 A* Z& n7 f) i - close(sockSrv); l5 w( ]8 l1 a# \5 V! y) B
- return 0;# X0 Z0 d" z1 U9 W$ }: K# W
- }
复制代码
' b1 t! ?3 k$ u+ T1 ^% w: R6 V; Y+ s( g# B! E
' q9 i1 W* Z% N, m" j5 ]
8 L1 l1 {& T }+ C2 v6 e |
|