管理员
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发
楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:
; Z, Z1 _" |4 ^9 u: E8 P3 f#include <sys/types.h>
: }" Z7 X. T5 q( r2 x N- K#include <sys/socket.h>
4 H* e- B" x1 U8 |7 M" l: a#include <unistd.h> ; {# @ k$ }! q8 i1 F! ]
#include <netinet/in.h> 6 h9 s |& d2 ~: R
#include <arpa/inet.h>
: } `+ e+ x1 l* `1 l/ q#include <string.h> + i& e" x j! X* X
#include <stdio.h> : ?4 W; @+ ?( P1 E
int main() {2 ` F! D& F* C! F( P% ^3 d b
int sockClient;% C8 c$ t* K' S1 w
struct sockaddr_in addrSrv;# Z* R0 }& d$ W, W) c) W7 |) C1 O
sockClient = socket(AF_INET,SOCK_DGRAM,0); d6 |/ G- Z# ~2 f4 G
addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");
5 T$ o% }4 i$ F2 _5 m addrSrv.sin_family=AF_INET; s$ Q' a3 G% N5 N6 O: ?5 A) V3 G
addrSrv.sin_port=htons(6000);
7 W* K8 P( q: O" } while(1)
( h5 o9 P. b' j8 h+ e. _# V {
: b) h* P4 x1 q8 w sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));
8 q* n8 _; T- t sleep(2);
/ b+ i5 Y% @- x# f$ Z; U3 c }
2 P e6 V( l: x0 j close(sockClient); : G, Z0 M, _4 I9 T1 M( a; @7 l# ?
return 0;
0 A1 X- t4 K$ y5 N}
, D, P% A. t: R+ s0 G& `1 @7 b( ~* E2 s: M1 D
9 t; M: }' D0 o
客户端:- #include <stdio.h> 5 N2 M3 w! y5 H; H
- #include <sys/types.h>
N5 {: E. [2 D s$ h& v2 N - #include <sys/socket.h> # O2 F4 u& v2 R+ `7 w6 L
- #include <netinet/in.h> ; x" H' y9 g# n, g
- #include <arpa/inet.h>
3 Q+ V- q U( z6 G/ a) R - #include <string.h>
. P3 x* l" r8 t, {1 N - #include <unistd.h> 0 |( a6 n) u- b- b6 |
- #include <fcntl.h> 7 _3 h- P6 m! C6 T
- #include <sys/time.h> + W" J5 r8 P$ `, |! l
- #include <sys/select.h> 3 \) h" F) a* Y# s6 |% v( G, y
- #include <sys/ioctl.h>
u- J" Z: c3 @( u* n) L - int main() {
5 e- \: ^$ V% W8 n - int sockSrv;
* {$ S& ~$ w( R7 c - struct sockaddr_in addrSrv;
0 t$ I9 A& ]. p2 R g - int len;
C, R# C) w' B- j5 o! L+ ] - char recvBuf[100];
: Q. B, \+ C5 _: T5 N - scanf("%s",recvBuf);7 z3 r3 A3 }3 c: E' g, J
- struct sockaddr_in addrClient;8 K3 |+ F* |! T, i. A
- sockSrv = socket(AF_INET,SOCK_DGRAM,0);
& r4 c& ~/ Z+ @9 V' W5 U - addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);" w1 y9 c# o8 H; g6 D |& H* m
- addrSrv.sin_family = AF_INET;
; D" B3 V, _3 b- G, l% s# d$ z - addrSrv.sin_port = htons(6000);
7 u: J& @! _, p2 O/ ^; J( v - bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));
3 Q M! `/ U W0 }# [& f - len = sizeof(struct sockaddr);4 \8 Q% k- f7 K
- memset(recvBuf, 0, 100);7 B1 C8 T& l% C! T
- recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);
0 N$ n, {/ K/ g; \3 j4 N; O+ a - printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));
: G, S& `: b+ | - printf("Client data is:%s\n",recvBuf);1 p! T- [+ }$ P7 C7 p: K
- close(sockSrv);9 D3 P4 P! U5 U8 f3 [
- return 0;( |" K5 S, t* Z( s
- }
复制代码
u* K4 o K4 L* ?9 D" g! F
1 ~ R. m4 k8 {) f5 x1 j( x. G$ z) E
. y9 d3 I0 J# s( P& z/ o |
|