Demo entry 6661415

c

   

Submitted by anonymous on Nov 22, 2017 at 01:36
Language: C. Code size: 1.3 kB.

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAXLINE 1024
#define TRUE    1

int main(int argc, char **argv)
{
    int sockfd, n, m;							//sockfd是socket描述符
    char line[MAXLINE + 1];
    struct sockaddr_in6 servaddr;				//address/port/family等结构体
    time_t t0 = time(NULL);	//时间秒数差
    printf("time #: %ld\n", t0);
    fputs(ctime(&t0), stdout);	//显示时间日期等

    if(argc != 2)	//Linux调用参数错误
        perror("usage: a.out <IPaddress>");

    if((sockfd = socket(AF_INET6, SOCK_STREAM, 0)) < 0)		//socket()建立套接口,sockfd小于0则显示错误
        perror("socket error");

    bzero(&servaddr, sizeof(servaddr));	//将servaddr清零
    servaddr.sin6_family = AF_INET6;	//指定地址协议族AF_INET6
    servaddr.sin6_port = htons(20000);	//指定端口 及网络字节顺序转换

    if(inet_pton (AF_INET6, argv[1], &servaddr.sin6_addr) <= 0)	//IP地址转换 字符串格式到网络地址格式
        perror("inet_pton error");

    if(connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)	// connect() 建立连接请求
        perror("connect error");

    while(fgets(line, MAXLINE, stdin) != NULL) {	//从键盘输入字符串
        send(sockfd, line, strlen(line), 0);	//send() 通过套接口发送数据
    }

    close(sockfd);	//关闭套接口连接

    exit(0);	//结束程序
}

This snippet took 0.00 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).