管理员
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发
楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:
& r* U# i" y) T3 D#include <sys/types.h> % o' P8 A6 [( H& F
#include <sys/socket.h> 7 w k# d2 u' y) r9 }, e7 Q
#include <unistd.h> ) _- J& J8 O% y, {5 H% O& e
#include <netinet/in.h> ( r7 W# H. j4 h9 c; Z( O8 r" S
#include <arpa/inet.h> ; I! D. W/ t3 n- C
#include <string.h>
2 h4 q( c3 d1 j) _4 p V#include <stdio.h>
1 W/ F. q- H/ k. R6 h3 fint main() {
" T4 L8 V( S' V$ Q# w V5 g) M int sockClient;
4 |+ p( ^8 t' l* b) }/ z struct sockaddr_in addrSrv;' J' @+ T- y# @( @9 j* d. K* a
sockClient = socket(AF_INET,SOCK_DGRAM,0);
9 v3 z6 Q$ @& N5 H7 e. Y* {5 j+ w addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");3 h9 c' `4 O$ s! i2 K, x2 C2 L
addrSrv.sin_family=AF_INET;
' M/ ^4 |3 W! q addrSrv.sin_port=htons(6000);) U9 s Q! O6 a4 V
while(1)+ u5 d0 ], s5 K$ v7 l' ?
{
! h! x2 L+ ]/ q( _5 A8 l sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));1 D( o% g' f2 |6 W f$ s0 Z* M
sleep(2);7 k S! x8 z) Z5 J1 ~2 ~; J- C% d
} 5 D$ \8 U- x) S: N! C! h& Y
close(sockClient);
+ ]8 c3 U" q6 K3 K return 0; ( X1 ]/ \% M% H2 l8 M+ D& q
}
- V8 k4 q/ p+ u7 A# a; E; e0 I) h" i9 q7 B+ y
6 q! B6 c1 }. ?/ C
客户端:- #include <stdio.h>
% y! F6 s: i6 _/ B) O& [ - #include <sys/types.h> + q7 s3 m' @ o+ k
- #include <sys/socket.h> * T$ M6 {5 u, I/ ]" G! z
- #include <netinet/in.h>
8 ^4 {- f7 O* C2 e2 O$ [! @# |" M8 H - #include <arpa/inet.h> 5 i5 \1 A8 P3 v5 K6 l7 ^$ J
- #include <string.h> 1 y3 m1 @* g" |7 `7 B3 u
- #include <unistd.h>
9 s+ j2 G3 V, @$ r - #include <fcntl.h>
& U. A, I$ d& [) w - #include <sys/time.h>
+ @8 o7 s0 I( D - #include <sys/select.h>
1 G( w" J2 r: o2 f - #include <sys/ioctl.h> : z) n& u3 ~1 K) M
- int main() {; I6 J0 V0 ~+ Z5 Z# G4 e' z3 B
- int sockSrv;
) U& `$ U3 X8 ] S - struct sockaddr_in addrSrv;
+ L: \2 b% M% C2 ^! S' g - int len;7 ~: y, {; L" s6 p6 v- u
- char recvBuf[100];" h; x9 Q( j9 q- Z; {
- scanf("%s",recvBuf);
' |& E9 t) k' E) s, N3 R* F0 v0 B' M2 y - struct sockaddr_in addrClient;) B, ]# ~) ~# ]2 ]: p
- sockSrv = socket(AF_INET,SOCK_DGRAM,0);" q {$ e) r6 y6 Z" S# O" J n: x
- addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);
) {$ U6 M% f( p5 P - addrSrv.sin_family = AF_INET;
9 E7 c3 w% u: T) I) Z; l - addrSrv.sin_port = htons(6000);
9 N8 I9 G9 H- F" ?. [. a5 t9 \ - bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));3 t( R; i, \, q9 h8 [) S, P8 A/ j5 h6 S
- len = sizeof(struct sockaddr);
/ c. m/ k! S9 R) S% _ - memset(recvBuf, 0, 100);% Z8 |( w' v# T# l2 J
- recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);# m& s1 r' y# R* f: @7 [0 s5 C" G
- printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));: R9 W- E, T4 k, u m- _7 d8 { x
- printf("Client data is:%s\n",recvBuf);
+ q! o0 @1 S+ t; v5 `/ k - close(sockSrv);
% s- m, ]5 A! l, f+ U! D - return 0;- x. s8 r( _0 ^" j' c+ ^) f
- }
复制代码 ' w" E0 U6 i, w; t5 A, X
& I$ f7 F* l7 O
3 Y8 t; r% t1 q# a% t& ?) Q2 z
. t9 ]9 d7 S$ t) U& _( j# N |
|