在UDP套接字上调用connect是一个完全的本地操作,并不给对端主机发送任何信息,只是保存对端的IP地址和端口号,并且同时也将给出了本端的IP地址和端口。
-
#include <unistd.h>
-
#include <stdio.h>
-
#include <stdlib.h>
-
#include <sys/socket.h>
-
#include <sys/types.h>
-
#include <arpa/inet.h>
-
#include <string.h>
-
#define MAXLINE 1024
-
int main(int argc, char* argv[])
-
{
-
int fd;
-
int n;
-
struct sockaddr_in server;
-
char re[MAXLINE];
-
char se[1024];
-
socklen_t len;
-
struct sockaddr_in client;
-
-
fd = socket(AF_INET,SOCK_DGRAM,0);
-
-
if(fd < 0) {
-
printf("socket error\n");
-
}
-
-
-
server.sin_family = AF_INET;
-
server.sin_port = htons(20000);
-
inet_pton(AF_INET,"10.155.3.243",&server.sin_addr);
-
if(connect(fd,(struct sockaddr*)&server,sizeof(server)) < 0) {
-
printf("connect refused\n");
-
}
-
len = sizeof(client);
-
getsockname(fd,(struct sockaddr*)&client,&len);
-
printf("local address %s:%d\n",inet_ntoa(client.sin_addr),client.sin_port);
-
-
while(fgets(se,1024,stdin)!=NULL)
-
{
-
write(fd,se,strlen(se));
-
n = read(fd,re,1024);
-
re[n] = '\0';
-
if(n >0)
-
fputs(re,stdout);
-
}
-
return 0;
-
}
编译运行:
gwwu@hz-dev2.wgw.com:~/test/socket/udp>gcc -g connect_udpclient.c -o connect_udpclient -Wall
gwwu@hz-dev2.wgw.com:~/test/socket/udp>./connect_udpclient
local address 10.155.3.246:17878
另外在某些系统中,如果服务器端对应的服务没有启动,那么对于已连接的UDP,将会在该套接字上收到服务器发送的ICMP端口不可达的报文,并提示“connection refused”。但是很可惜,笔者在test的环境中没有模拟出,应该是系统不支持吧!
阅读(710) | 评论(0) | 转发(0) |