管理员
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发
楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:
* Z" |, K/ x9 q9 Q7 W#include <sys/types.h>
' S' N! ^7 T5 j$ u1 h7 Y0 g#include <sys/socket.h> ) z7 T: V* T8 U" H% k" }" l
#include <unistd.h> 6 ~& |/ b& ^8 S% x2 u& h, c) X
#include <netinet/in.h> + [+ V4 @& a' q* {( W# _
#include <arpa/inet.h>
+ n7 z3 E; g5 a1 g#include <string.h>
; A# Q# U8 h+ a( e, \4 E#include <stdio.h>
: c) x5 x4 u) _1 vint main() {
% b: S' Q# R2 a+ \* k8 T' { int sockClient;
& G J* D+ L- f+ j# N1 b struct sockaddr_in addrSrv;
2 j5 T4 _. K( t' F sockClient = socket(AF_INET,SOCK_DGRAM,0);
- F2 O: E; W6 [7 X g addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1"); [# l; W' }( r4 P
addrSrv.sin_family=AF_INET;1 G+ w1 o; @( v# U' r; _& V
addrSrv.sin_port=htons(6000);
, L5 H/ a3 |/ p0 ]. R. X while(1)
! d- e8 ^ W) m t0 b( q {1 d! A5 |" e9 h6 U }
sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));/ U# H; z5 _3 v/ Y5 m. ]
sleep(2);) E+ t8 P# q( U: \# m/ k5 y+ E+ H
}
" k3 Q( I5 e( L8 p- H! ]- [ close(sockClient); / i$ z3 k7 I. w' n) J
return 0;
4 G+ e4 _1 t( o}
0 w5 P& u" P/ y# I2 `
7 p+ [& P& G: b+ u) K/ g$ C9 B8 e
& s8 B: x8 [2 w7 v2 I) D0 k客户端:- #include <stdio.h> : G7 B' O" I0 z+ |4 {: i3 E
- #include <sys/types.h> 1 x* V' p5 T$ k& d% C% S1 a
- #include <sys/socket.h> $ m2 j! U) e; E1 K9 v1 z, W
- #include <netinet/in.h>
9 { L% |$ k0 l1 \, @ - #include <arpa/inet.h>
* \/ s; F& r; Z% Q5 o - #include <string.h> + T- B: [" s! v: i" i6 [
- #include <unistd.h> 5 N( s- M6 x& o6 n6 D* x4 |- ]6 K
- #include <fcntl.h> / |" P3 k3 f) }# W E
- #include <sys/time.h>
. B" k, f$ D2 q) u% ~ - #include <sys/select.h> 5 W! W$ C+ @8 v: s1 T- \6 u, N
- #include <sys/ioctl.h> 3 |- s* M8 b/ W" Q4 J
- int main() {
: N3 T. J4 p2 K3 y- `" U# Z - int sockSrv;
1 E/ f: V* b; r' b4 A - struct sockaddr_in addrSrv;
Z" Q9 y, M6 f - int len;
0 l6 _( Z7 _- M9 l - char recvBuf[100];. f: Y" ~% [7 a8 E. Q
- scanf("%s",recvBuf);
4 n! E. s1 S& K7 ~ N - struct sockaddr_in addrClient;
+ q- U- |$ J j4 w x* C: s; J+ ` - sockSrv = socket(AF_INET,SOCK_DGRAM,0);
6 F9 `6 o) g+ F, ^ - addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);
# u+ ^7 V. \/ o" X& t - addrSrv.sin_family = AF_INET;7 w: g3 }: S" } g# N+ ?
- addrSrv.sin_port = htons(6000);
& P( L0 O. L2 J9 h7 r- Q1 m - bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr));/ d5 w6 g# J j; b- s. I
- len = sizeof(struct sockaddr);) M1 E# b4 E! ?; C+ k+ s; y
- memset(recvBuf, 0, 100);: v. T3 i) ]( w# Q
- recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);3 J$ y2 ?3 e/ {
- printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));
" V; z+ m3 F; X - printf("Client data is:%s\n",recvBuf);
0 G6 e/ Q5 t1 i% o7 G - close(sockSrv);
( F' I. Y; J& A1 E - return 0;
3 Q# b' H5 W8 x: y - }
复制代码
+ g; p/ P1 f4 n8 d( u- {0 } I% S) g
0 d( [* P* ~2 z* c1 I) G% O* w9 [4 M3 t1 n" Y" @* ^
|
|