tcp.c

来自「支持ZModem, Telnet功能的串口通讯程序」· C语言 代码 · 共 57 行

C
57
字号
/* * This function sets up a tcp call to the the machine specified in the passed * string. if the machine name is followed by a colon then a specific tcp * service may be specified, else the telnet service is used. A file descriptor * to and from the machine is returned or else -1. */#include <string.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h>#include "virtmodem.h"intcall_tcp(char *c){    struct in_addr sock;    struct sockaddr_in a;    struct hostent *entry;    struct servent *service;    char *servicename;    int fd;    /* look for alternative service names */    servicename=strrchr(c,':');    if(servicename) {	*servicename='\0';	servicename++;    } else	servicename="telnet";    /* try to make a socket */    if ((fd=socket(AF_INET, SOCK_STREAM, 0))==-1)	return -1;    /* get machine either by name or by IP address */    entry=gethostbyname(c);    if (!entry)	sock.s_addr=inet_addr(c);    else	sock= *((struct in_addr *)entry->h_addr);    /* setup the destination port */    a.sin_family=PF_INET;    service=getservbyname(servicename, "tcp");    if (service==0)	return -1;    a.sin_port=service->s_port;    a.sin_addr=sock;    /* attempt the connection and return */    if (connect(fd, (struct sockaddr *)&a, sizeof(struct sockaddr_in))==-1)	return -1;    return fd;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?