管理员
   
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发

楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:: T2 {) }: _5 _( J3 M
#include <sys/types.h>
( b+ f1 a" [ c1 z7 v, }# A#include <sys/socket.h> 7 o; E2 m7 t) b+ y) S. g% ~
#include <unistd.h>
T6 t* K: H$ ?1 K: }#include <netinet/in.h>
~# |! J! Z" o#include <arpa/inet.h> : O( G9 u* N- R" j! g- r2 B S
#include <string.h>
2 \" R8 d0 c" d1 [* [$ g; n* D#include <stdio.h>
r, i3 b! V! v, T- b- b" U/ Oint main() {
5 s# \4 e- W% u' ?: L int sockClient;
5 l' `/ l( s6 V: K7 s# `$ C' p" C struct sockaddr_in addrSrv;
$ |1 Y* D! X0 H9 W4 y sockClient = socket(AF_INET,SOCK_DGRAM,0);
" ~. g% N% b. K7 @( p; N5 x- ` addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");
- Y0 V0 e5 x; H+ ]& ]9 ?5 a1 w; u! } addrSrv.sin_family=AF_INET;
4 I/ d' ?- q# n8 v4 G0 O addrSrv.sin_port=htons(6000);7 q4 |5 t% U# c( ^8 M
while(1)+ e9 s. O2 M4 b6 `8 X/ Y) q
{
5 d' c- f- e+ j( A( g sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));
: D. x; M7 ^+ V4 V* p! F sleep(2);
( y: c$ Z3 u+ L } $ x$ g T' y# H4 n
close(sockClient);
7 J- z; n& U1 f& H$ K5 d return 0;
/ U1 q/ G0 V' D% y- N* g$ A}
( u- G' U( e( d# c" t" Z" n9 Z5 z/ c
3 `9 C$ l1 s+ G% v) S. u/ k5 Z
客户端:- #include <stdio.h>
$ ^$ \' {2 X, n A, p- \* z! d$ U - #include <sys/types.h>
0 Q0 A7 V2 H' u) N- _6 x! M$ T3 w - #include <sys/socket.h> ( z2 A* s/ z3 \ m; ^
- #include <netinet/in.h> & D7 B9 \- W+ U, V+ B
- #include <arpa/inet.h>
' L4 n; E, Q, e$ @8 Z& ~3 C; W - #include <string.h>
* M5 D" c/ k" h( `( c: g ] - #include <unistd.h> ; J8 Q$ q3 e( v% u
- #include <fcntl.h>
+ R' o: g6 r) D: }; A1 N2 b! j1 R - #include <sys/time.h> & w; Y7 K4 J+ a
- #include <sys/select.h>
( Z3 _- A% e$ R; v2 k' b8 q0 \ - #include <sys/ioctl.h>
' E/ v/ z- n9 V7 _ - int main() {+ y0 o* s4 O! V8 Y# @
- int sockSrv;) ?* I, C- ^+ H, _
- struct sockaddr_in addrSrv;
: x0 T. ^; S9 K9 c - int len;
( F& D$ } v5 M# \ - char recvBuf[100];
1 ]; b- u# i0 j6 f1 `+ j; g - scanf("%s",recvBuf);9 `; l; h1 g5 {
- struct sockaddr_in addrClient;) w$ `3 [9 S7 A
- sockSrv = socket(AF_INET,SOCK_DGRAM,0);
) Y! D! h! }/ {( z) G! ` A& A7 u( D - addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);2 O8 W6 G' g- n" H& p
- addrSrv.sin_family = AF_INET;9 [1 p8 ]% j3 N4 u2 D! T
- addrSrv.sin_port = htons(6000);% }$ Q0 Y2 {$ ]9 m1 t6 H# g: w
- bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));$ W1 k( R2 w# }+ w
- len = sizeof(struct sockaddr);
. y0 Y+ [; u& _ - memset(recvBuf, 0, 100); Y/ [" S2 G9 [8 ^) M6 M& @6 o
- recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);8 I0 w* j. r5 }- ?7 f8 W& s1 \& S% M
- printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));2 |+ v5 _' ^* f0 }5 z7 \
- printf("Client data is:%s\n",recvBuf);
! j4 y+ L! ]4 g- H - close(sockSrv);. v( o! o3 u/ f5 a6 g$ X* h2 U# a
- return 0;% j9 l% L" J( U; l
- }
复制代码
( J) E8 `% [' A& e* O
4 G! {% o9 p: x4 B* p( g$ L* z1 z% k4 L% {- V! \' n0 B, ^
. l. o" b/ r3 k |
|