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

楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:
7 O: L; K- E9 s. Y: I# ~#include <sys/types.h> 4 Z3 a: s4 `" c" F$ d$ K: @
#include <sys/socket.h>
3 S" ^% K. l! G, e0 s#include <unistd.h> 5 g- l( e" T1 w1 C% @
#include <netinet/in.h>
+ E8 r0 y! `) i/ M& N#include <arpa/inet.h> 5 q0 x9 o1 j" N2 {: R- X
#include <string.h> 1 N6 A& c) l9 N' ^
#include <stdio.h>
& I8 ~, Z, C) p: k4 T$ ~! t" Aint main() {
% T4 V% J" N3 H' d int sockClient;
6 u7 ?1 N+ C6 ^* K struct sockaddr_in addrSrv;
) ?6 I8 p' o% N% S7 O1 [ sockClient = socket(AF_INET,SOCK_DGRAM,0);
6 J: ]/ [0 ^ d8 y. a addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");5 F- T/ e& e) C& a3 r: G: ~
addrSrv.sin_family=AF_INET;% a( z6 G- `6 Y, w) k
addrSrv.sin_port=htons(6000);
, S3 r& S) ^) A. b while(1)
: c9 h% f4 _5 b$ D b) W {
2 @- k r: o- i- U Q+ g# O' Z sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));( B7 B9 ]8 i2 L$ o6 g6 ^' J
sleep(2);
! k; k; {# W* e i; Q }
+ B9 \* O* y7 o* c8 X4 S close(sockClient);
! X6 c" Y, C. e: P return 0;
/ G7 m8 Y/ N( ^9 d8 m$ U1 h3 y}
; v5 R, A( Q! I8 t0 l4 d/ s1 {
2 t! ^2 Y& f, Z, l- C
% `0 u* M# j% p( H. n; S客户端:- #include <stdio.h> S# X9 P( @3 n" {1 |; S
- #include <sys/types.h> ( R7 U. G7 G" a: X @; B$ l4 F
- #include <sys/socket.h> 0 r. Z( x- P6 L+ C
- #include <netinet/in.h>
4 J( p$ [4 z J8 o! v* f - #include <arpa/inet.h> / Q6 u+ }5 D5 J3 c
- #include <string.h>
% J/ T4 d) a! w; p/ i3 V; w - #include <unistd.h> $ ~6 ^: l* b1 u0 Y/ R6 ^ H4 F
- #include <fcntl.h> 0 W* g! Q3 K" ]4 ]6 q2 j, [
- #include <sys/time.h> . G7 W& Q5 |8 k, w+ Z' V
- #include <sys/select.h> % x3 R6 A3 W) G4 @) t9 Z& C2 _' B
- #include <sys/ioctl.h> 0 k* ] B* z( n! R. C: ^
- int main() {5 y8 y6 _, N4 J5 V) ]4 p. p
- int sockSrv;: r5 {- O% Q2 P6 h7 J, A- B$ b
- struct sockaddr_in addrSrv;5 Y- Y& m0 V/ N
- int len;1 {. A) [2 a1 h' r, b: I# T6 f3 G
- char recvBuf[100];
$ J3 z2 A! _1 a) ~2 q8 i# Z - scanf("%s",recvBuf);9 h) z( ^$ G$ p! s
- struct sockaddr_in addrClient;
! x: g+ V" ]5 D& F - sockSrv = socket(AF_INET,SOCK_DGRAM,0);
/ S' g( u! D8 l. n6 K3 t; e+ _9 K! B - addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);% E4 s& b z0 o. {
- addrSrv.sin_family = AF_INET;0 d# F/ H8 Z1 |9 Q" [
- addrSrv.sin_port = htons(6000);4 P7 R1 A' R/ I4 q v3 x' V# V9 J
- bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));& j3 l8 x |2 v
- len = sizeof(struct sockaddr);" |' t' n; [; u9 s9 M+ N
- memset(recvBuf, 0, 100);
s* r4 o0 R- z: }: H - recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);
* O/ F9 r( X8 R6 X" d2 {- J - printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));
6 H" [6 U: e n" x2 T - printf("Client data is:%s\n",recvBuf);
$ `: X. m5 E# d" v5 U% T7 C2 Y - close(sockSrv);
9 B; J8 @" w+ |* z/ d& @3 T" I - return 0; Q+ r. k) `* s$ T
- }
复制代码 $ d! U9 U+ S2 M1 }2 r1 F
+ A2 R- n! p% Q; P
7 Y" y1 q( c. c) H2 k9 N2 b( @$ R' Z/ V, P; n) D1 N0 U
|
|