管理员
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发
楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:8 v* _8 B J+ ?, z
#include <sys/types.h>
U! g! Q& y4 L$ V8 ]% k8 Q$ {#include <sys/socket.h> 5 x1 C3 F+ x6 \/ V
#include <unistd.h> 3 \# a6 A/ R& j7 d6 e4 G
#include <netinet/in.h>
8 A! L, E* Z. I* x9 q3 F* n5 a#include <arpa/inet.h> " S1 ?# |% H# b( E) M8 h: s/ h% s% }2 y) }
#include <string.h>
2 Z7 l) p/ F- L4 E6 q: t/ I/ ~#include <stdio.h>
0 o* R8 e+ s' j: Q+ N, {' Xint main() {! u! E" y* Z4 T2 m5 a. E" j0 v
int sockClient;
0 Q7 w6 r4 P7 [* F$ X {) m, B* c struct sockaddr_in addrSrv;
! m3 U# N' B" [ sockClient = socket(AF_INET,SOCK_DGRAM,0);. X1 {5 ^6 w0 b e
addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");$ F& ?- Q% j" J0 z. ~
addrSrv.sin_family=AF_INET;
1 {. q9 y) W- Y$ c7 m- \ addrSrv.sin_port=htons(6000);
. A6 G, z0 N5 p) @, k while(1)" i; I3 m$ o% w1 W1 D" Z% `; c
{
2 ?( q+ H! t4 G9 ^* f/ [ sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));
1 I0 }8 E3 M0 b sleep(2);
. n2 P% m4 w. u$ o% c0 P9 Q } : t( r7 U2 f8 ?6 N4 T1 d+ b6 t" |
close(sockClient); 0 W$ {3 g+ Z7 O! r
return 0; 2 \4 x1 o! Q5 u; O! P# n
}+ j! u8 W5 I/ |: l/ }' d! V& _8 e) |
* j2 x# B' \9 a
" `1 ?5 L! x6 u2 e2 |客户端:- #include <stdio.h>
) k- d! f. K' o- {/ k9 _ - #include <sys/types.h> + H4 l, S! B9 B; R1 \, N
- #include <sys/socket.h> + i* u( c* Y7 }# Y
- #include <netinet/in.h> ! ^; V1 p) [* L, g" z! X6 U- ?2 W9 y
- #include <arpa/inet.h> 3 s! K, p: W3 B1 M- Q6 y
- #include <string.h>
' a X Q& u1 O+ d$ z, u - #include <unistd.h> & a: p/ x( p- d5 m. E2 b6 [
- #include <fcntl.h> & H9 E3 @9 Q5 I% y% n1 y
- #include <sys/time.h> 6 |3 G3 ~- o! K! i
- #include <sys/select.h>
0 ~9 N' V/ @% o5 Z4 s% G6 a - #include <sys/ioctl.h> 1 J* ~) W; S' p) R# D
- int main() {( W( x Y# w& a W/ k
- int sockSrv;
. ^7 {2 d- V$ _' T, y$ D. B* u2 k& M - struct sockaddr_in addrSrv;* z; f0 {! w, Q2 R
- int len;
y# q) c2 B5 ]% `( w& S2 L7 I - char recvBuf[100];" `+ I7 Z( C$ e+ [, E' C6 A
- scanf("%s",recvBuf);1 t( d, T" H8 a/ f# r1 J0 a- p
- struct sockaddr_in addrClient;
. @; t+ x3 e; R, H9 q. e+ y - sockSrv = socket(AF_INET,SOCK_DGRAM,0);& Z; p+ }, b. O" {; L3 N$ w
- addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);) S. J: ?) t5 d" L- Q, _' f
- addrSrv.sin_family = AF_INET;
2 ^8 G! s5 H7 l% [( n$ G - addrSrv.sin_port = htons(6000);
- U: H0 e$ Z2 U" p- _" w) U C - bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));
% i3 q3 N; c9 B9 t( ` - len = sizeof(struct sockaddr);5 m8 B2 [4 k/ M5 k
- memset(recvBuf, 0, 100);" y7 ^9 E4 n& h/ U! \3 h8 M
- recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);
$ ^; r8 ~; y& N3 ? - printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));$ N' H2 _* l, D9 A+ X8 m
- printf("Client data is:%s\n",recvBuf);! W; J7 ?3 O) |$ X2 A
- close(sockSrv);7 x+ x3 X( u% Z W1 i! t' w6 a
- return 0;
. _9 V) K- T* ` - }
复制代码 ( V( m+ n$ z7 T, D$ w* V5 J
: x, u+ b# Z* A. q: ?: C3 }
+ k! z$ }% W2 G
$ W6 c4 R- y8 t( |& ]4 A
|
|