管理员
论坛积分
分
威望 点
贡献值 个
金币 枚
|
沙发
楼主 |
发表于 2020-5-9 02:30:12
|
只看该作者
服务端:/ y/ T. x) S5 t+ a$ k3 X% B
#include <sys/types.h>
1 o0 F: W9 U6 k; v#include <sys/socket.h> 1 M3 U( Q: w4 |, b
#include <unistd.h> ) D1 B" b3 w, F5 J1 m; H% b3 s- \
#include <netinet/in.h>
% o9 W1 R8 u: Z$ z2 l#include <arpa/inet.h>
- k7 C7 ]) d! a/ L5 Y; {( N& {' @3 |#include <string.h>
6 {# F8 q$ j/ o#include <stdio.h> ' K; E( v* J; f0 `& b8 Z! z
int main() {9 W/ B# t2 H/ n. X8 w: s* u$ H
int sockClient;
; I! l8 ]0 a) ]6 v. i! s struct sockaddr_in addrSrv;7 f8 t- |' Q! `# }- e- o
sockClient = socket(AF_INET,SOCK_DGRAM,0); _: J8 j5 V1 @0 R/ `& g
addrSrv.sin_addr.s_addr=inet_addr("127.0.0.1");
+ D- k9 V8 ^1 F) Z" x0 o addrSrv.sin_family=AF_INET;; @2 l3 a D5 d8 h) k5 ], j
addrSrv.sin_port=htons(6000);
! X; _6 T/ n- r" s& e while(1)% ~& ~* t& P/ A) ]$ T' t/ q
{. ~2 g: i u: M! j% Q2 S% V
sendto(sockClient,"Hello World",strlen("Hello World")+1,0,(struct sockaddr*)&addrSrv,sizeof(struct sockaddr));
+ z; L6 n5 |0 O$ v sleep(2);& s9 Q% O, Q, A' h+ b
} - z$ Z3 B {: }' i: i1 i- r
close(sockClient); $ Y1 t* [# E4 `8 i. c
return 0; 9 q" b$ Y; s( N: U/ W7 a
}9 p5 z! r# t2 ]+ A2 b: S. v
/ B4 `- Y" Y; n3 A
' _$ O+ Y* G2 j1 O4 n/ b7 w客户端:- #include <stdio.h>
6 D* y6 N4 w: J- [1 n$ G - #include <sys/types.h>
3 t3 O# E1 ?/ n# n* A - #include <sys/socket.h> Z. G2 {% `* F! m6 C1 y- B# j8 V7 i
- #include <netinet/in.h> c- D9 I7 Z/ K5 P4 J
- #include <arpa/inet.h> % W- D4 @9 ^5 E. ~( |, `2 J( j' w
- #include <string.h>
" S+ q& ]4 Y8 m0 D9 P) i) U5 } - #include <unistd.h> 1 ]2 L" m8 W& x; _/ t+ I, {
- #include <fcntl.h>
* @. N+ J$ Z7 \ - #include <sys/time.h>
! f) r4 T$ n" M+ Y" ] - #include <sys/select.h> 5 y$ }' M8 I+ ?, L8 S
- #include <sys/ioctl.h> 9 X4 M h) n+ d
- int main() {
+ ^' g+ K1 E+ A) w* y2 M% J - int sockSrv;
( ^/ s# |( b9 W! C, r+ | - struct sockaddr_in addrSrv;
" g. K/ {4 ]% H4 V - int len;
4 k; V3 N, z( e8 B" A - char recvBuf[100];
6 ]0 r4 t, _/ h& r5 y - scanf("%s",recvBuf);) x0 G/ g8 A r9 u5 ?: Y5 d! |
- struct sockaddr_in addrClient;
' M$ \' h; _' e9 w - sockSrv = socket(AF_INET,SOCK_DGRAM,0);- V, c2 b/ q1 F d
- addrSrv.sin_addr.s_addr = htonl(INADDR_ANY);, B- Q% m9 _4 U$ v
- addrSrv.sin_family = AF_INET;+ x& }' g0 r+ b* \8 @6 f
- addrSrv.sin_port = htons(6000);
( K, p9 S2 c$ p% I - bind(sockSrv, (struct sockaddr *)&addrSrv, sizeof(struct sockaddr)); \2 S* c0 h6 A% e& y5 s" ] r; h
- len = sizeof(struct sockaddr);( r* Y4 b6 `: P( |4 O) P
- memset(recvBuf, 0, 100);. a8 C7 ^. u! U; C$ w
- recvfrom(sockSrv, recvBuf, 100, 0, (struct sockaddr *)&addrClient,&len);! i/ b- j1 r2 b! g" j
- printf("客户端的IP地址:%s\r\n",inet_ntoa(addrClient.sin_addr));
' S6 q7 w5 a3 c) f; I6 A - printf("Client data is:%s\n",recvBuf);: ] b4 ?: u& p& E/ m
- close(sockSrv);
; P- A/ ]8 X' B6 C/ s - return 0;0 \7 @, }9 T. a* u ^# j
- }
复制代码 ' L& I" a; C+ E1 r
/ h9 g4 N# d1 G' O
% {3 u$ D7 z6 s8 l1 t/ J& c' W7 q( F( p( X- r
|
|