管理员
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发
楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:
- e$ e5 i6 X+ ]9 s' ] k, @#include <sys/types.h> & l2 c# ?" j, F& Q/ m
#include <sys/socket.h>
/ e3 E. M) e) {8 Z4 M. U#include <unistd.h> % K+ u; T$ h' U( u
#include <netinet/in.h>
' a9 ^3 ^4 h% v#include <arpa/inet.h>
7 f W/ {4 h* r& {5 \#include <string.h> & B; I/ X4 ~3 H n+ ?; {2 b
#include <stdio.h>
2 T( Y( L4 g$ N# w2 wint main() {/ w T- ?7 _' P) q) a5 ` k
int sockClient;$ p o( `% w. R; K5 G
struct sockaddr_in addrSrv;
0 |5 ^# f7 ]2 g4 _' m8 w1 Z sockClient = socket(AF_INET,SOCK_DGRAM,0);
' k6 i4 `/ n/ Q+ o addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");
% l0 l r! O" h7 g! }6 |1 \ addrSrv.sin_family=AF_INET;
0 N1 e D" P6 k: z, A addrSrv.sin_port=htons(6000);: j* D4 G; `' N* s
while(1)5 Z6 l4 x/ V/ T$ h$ c2 a1 ~/ }+ F
{! m9 u! H3 O" s$ C4 E) T
sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));
1 l% D8 P0 X9 a sleep(2);
M2 N: w# `/ m0 L2 g) I }
8 X: L* t- C9 ] close(sockClient);
# n. d9 P5 y! o; T return 0;
# Z$ u; |. t% a}
1 D6 q+ `$ i; i* f% d
% @, S! k. O7 U0 V6 `: n+ y z) v, N9 Z. L r3 S9 |
客户端:- #include <stdio.h>
0 K3 l- D/ O1 o* M6 [6 r - #include <sys/types.h> / [" H# [! L! K+ @7 _6 _. J
- #include <sys/socket.h> 7 d3 d% D+ R* M. V( h
- #include <netinet/in.h>
, w' j8 E( m& z# i! }: e - #include <arpa/inet.h> $ g$ ~; m5 t$ o4 s
- #include <string.h>
' Z/ C2 Q* @ R) Z, }7 y - #include <unistd.h>
$ ]/ _. N& q- K - #include <fcntl.h> 8 L4 O% ~# R% y) y# e5 k6 ~
- #include <sys/time.h>
) L9 ?0 r: g8 N" ` A/ K - #include <sys/select.h>
- e4 p% s" _; k( J - #include <sys/ioctl.h>
& d' m: h F7 ~/ K9 o - int main() {' f3 G; M4 J; I& C7 P* x
- int sockSrv;
: I7 Y/ w3 l) H# V' R - struct sockaddr_in addrSrv;
% I) k5 x4 d1 s* @% K; [( _- B - int len;' W" g$ D& z) b1 f' T9 X
- char recvBuf[100];
2 B0 M% Q1 H& e9 R - scanf("%s",recvBuf);
( \5 u$ Z8 J* _2 Q9 m6 c+ g* ?! H6 D - struct sockaddr_in addrClient;
4 h) E( n$ c" M3 d0 e r - sockSrv = socket(AF_INET,SOCK_DGRAM,0);
0 s1 u& P8 `/ @! g; z9 r - addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);
, n- D: N7 h* z1 e - addrSrv.sin_family = AF_INET;$ ]' w. {1 Y; Y x1 s8 D
- addrSrv.sin_port = htons(6000);
% ~; c/ L8 \; f( \6 a- K - bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));
. R3 k; ^& A) B* f. ~3 O - len = sizeof(struct sockaddr);
, U' i' K; J3 T7 X5 v7 Q2 A - memset(recvBuf, 0, 100);/ r( x' [7 I% u! B. K4 E/ b2 |
- recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);4 N3 A' ]5 v( k- B( d2 I3 n
- printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));
* T8 O+ X* q* d' [0 Z* E - printf("Client data is:%s\n",recvBuf);
4 A+ A) \# m2 ] - close(sockSrv);
& G0 H! }8 d, A$ K9 l - return 0;* u% s' A5 l, G9 U5 e
- }
复制代码 3 o; B. p+ I" r0 K" d f2 h/ G
0 X/ ]( a+ A$ Q. ]* f4 Y/ H
( H. X: `5 c( T H) H
, ? w% S8 k3 D1 {/ x8 x |
|