管理员
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发
楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:
* b* D6 C7 K3 y0 c% P#include <sys/types.h>
' o; Y" T- F3 u: |; G#include <sys/socket.h>
, Z9 |" {6 I& \# y#include <unistd.h> 2 p* D9 r3 }9 @4 t& |, i) Y
#include <netinet/in.h> " g/ Y" p3 a. f) Z; A7 h+ m
#include <arpa/inet.h>
4 X& [: F$ O2 W; l#include <string.h>
9 |7 Y2 U5 v0 C, Z0 w5 v4 A. G: W#include <stdio.h> Z- G i1 J" w/ k7 s
int main() {$ h/ `0 A1 d; } C2 ?0 T0 k9 ]
int sockClient;
* U9 _1 c9 P n& F( {% ]' l struct sockaddr_in addrSrv;
5 A( Y: ^3 E0 b/ | sockClient = socket(AF_INET,SOCK_DGRAM,0);
1 F' n, m) Q% d: I' `- o' G addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");
$ \5 C$ C8 H1 b addrSrv.sin_family=AF_INET;
" u+ |8 {! Y1 C' q2 _9 j addrSrv.sin_port=htons(6000);
" c% l! l( w5 D# |8 X9 a- s9 L$ n while(1)& l5 y% {( C+ r- C6 @
{" |; Q" f1 `' U% K% P
sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));. ]1 I" k( G/ v& a
sleep(2);4 |5 v5 J) ~5 u/ s3 E5 A2 b; ~
}
7 |: ?; G ^- M7 ]8 j close(sockClient); . t0 p, j- ~- Y" l9 Z. \
return 0;
* O9 W9 I }* y" c; G}( T* [2 S8 v( c; S9 Y1 {! M' I/ G
& `# A3 ~0 |2 A5 i( P% I
. ~7 d8 }. ~; o6 V( C客户端:- #include <stdio.h> & I/ M' D( Y$ ?- o# p
- #include <sys/types.h> $ T, N: k/ @: T. O6 M
- #include <sys/socket.h>
' z1 }9 y5 a" k+ `* Q$ C. {; { - #include <netinet/in.h>
7 J# O1 ?6 s! V9 N) Y `+ @- D+ ~ - #include <arpa/inet.h>
8 ?2 L( ]4 ^8 a v7 k) ^ - #include <string.h>
: E* K/ e, @3 f) E+ w - #include <unistd.h> 5 I. \' l% S. B% R
- #include <fcntl.h>
. T1 e5 }+ f# _) Y0 T, O - #include <sys/time.h>
n/ z- _7 [ I: n/ r6 j9 l - #include <sys/select.h>
7 z5 i5 s+ c/ x y5 G# m - #include <sys/ioctl.h> : O: Y3 e$ [" t8 v' C
- int main() {
( a; }8 y9 C3 Y8 i; _' y* W - int sockSrv;
: W' p) N7 [% _# P* Z8 v - struct sockaddr_in addrSrv;
! w! W. Z, j7 h! ?4 _( _ - int len;
- m/ E3 Z' O2 B4 e [0 s1 s2 ~ - char recvBuf[100];
# G; U7 `* A. x3 z1 {1 [ - scanf("%s",recvBuf);1 h' H* a( @( l7 }! @4 \
- struct sockaddr_in addrClient;
. o7 F, d2 e) ?# X9 w$ u8 o - sockSrv = socket(AF_INET,SOCK_DGRAM,0);
& v1 B3 L/ U/ v+ J - addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);
6 x: G, q# l/ S. z4 [, d+ v - addrSrv.sin_family = AF_INET;
4 _# z$ W' h7 Y, [; N5 o - addrSrv.sin_port = htons(6000);
* m# q3 M! F- i! s - bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));; j; ?- B5 H( s& H, r
- len = sizeof(struct sockaddr);
6 Z" E$ J' G' ~' h1 T+ i6 l - memset(recvBuf, 0, 100);2 h2 N% S( F% f0 P/ B! W
- recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);% |: p% }) U5 r
- printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));6 T5 Y( N$ w' T+ W! B+ v! \
- printf("Client data is:%s\n",recvBuf);
3 R- b5 e# s8 @8 K9 c+ Z8 l, X - close(sockSrv);
) L$ g* H8 R0 n6 }3 `5 Q& [ - return 0;, W& `8 L) l! V/ P
- }
复制代码
# Z5 e0 B& y! F) [* `) S4 s$ a
, @0 {& z1 i' U/ ?) M4 ]" o
# g) P, O& n6 c; ]9 O9 K3 i, a4 T
" |8 M+ W( q7 Q$ h% C8 v |
|