日期:2014-05-16 浏览次数:20806 次
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#define MAXLINE 1024
int main()
{
int sockfd, n;
char recvline[MAXLINE + 1];
struct sockaddr_in servaddr;
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
printf("socket error");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(8000); /* daytime server */
if (inet_pton(AF_INET, "127.0.0.1", &servaddr.sin_addr) <= 0)
printf("inet_pton error for ");
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0)
printf("connect error");
struct sockaddr_in ss;
int len = sizeof(ss);
if (getsockname(sockfd, (struct sockaddr *)&ss, &len) < 0)
return -1;
static char str[128];
inet_ntop(AF_INET, ss.sin_addr, str, sizeof(str));
char portstr[8];
if (ntohs(ss.sin_port) != 0)
snprintf(portstr, sizeof(portstr),":%d", ntohs(ss.sin_port) );
while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {
recvline[n] = 0; /* null terminate */
if (fputs(recvline, stdout) == EOF)
printf("fputs error");
}
if (n &l