unix代码示例:一个socket客户端程序

代码:模仿telnet访问newsmth bbs,打印第一次收到的应答后即退出。

#include <stdio.h>
#include <unistd.h>
#include <netdb.h> 
#include <errno.h> 
#include <sys/socket.h> 
#include <string.h> 
#define MAXADDRLEN  256 
 
#define BUFLEN     500 
 
 
void print_resp(int sockfd) 
{
    printf("ready to print response\n"); 
    char    buf[BUFLEN]; 
    int n; 
    int i; 
    for(i = 0; i < 5; i ++){
	n = recv(sockfd, buf, BUFLEN, 0);
        write(STDOUT_FILENO, buf, n); 
    }
} 
 
int main(int argc, char *argv[]) 
{ 
    struct addrinfo *ailist, *aip;  //ai是addrinfo的缩写
    struct addrinfo hint;  //从服务端拿到的addrinfo可能很多,需要使用hint来过滤。hint对象本身也定义为addrinfo类型
    int             sockfd, err; 
 
    hint.ai_flags = 0; 
    hint.ai_family = 0; 
    hint.ai_socktype = SOCK_STREAM; 
    hint.ai_protocol = 0; 
    hint.ai_addrlen = 0; 
    hint.ai_canonname = NULL; 
    hint.ai_addr = NULL; 
    hint.ai_next = NULL; 
    if ((err = getaddrinfo("newsmth.org", "23", &hint, &ailist)) != 0) { //生成addrinfo
        printf("getaddrinfo error: %s\n", gai_strerror(err)); 
	exit(-1);
    }
    printf("getaddrinfo success\n");
    for (aip = ailist; aip != NULL; aip = aip->ai_next) { 
        if ((sockfd = socket(aip->ai_family, SOCK_STREAM, 0)) < 0) //生成socket对象
            err = errno; 

	printf("make socket success\n");

        if (connect(sockfd, aip->ai_addr, aip ->ai_addrlen) < 0) { //连接
            err = errno; 
        } else { 
            printf("socket connect success\n");
	    print_resp(sockfd); 
            exit(0); 
        } 
    } 
    fprintf(stderr, "can't connect to the target: %s\n",  
      strerror(err)); 
    exit(1); 
} 

运行: ./a.out

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.