C学习 - Linux下的Tcp Client

#include 
#include 
#include 
#include 

#define SERVER_PORT_NUM 5025
#define SERVER_IP_ADDR "146.208.235.229"
#define ERROR -1
#define OK    0

int tcpOpen(char *  serverName     /* name or IP address of server */,
        int serverPort /* port */);
void tcpClose(int fd);
void tcpWrite(int fd, const char* cmd);
char* tcpRead(int fd);


int main()
{
    char *str;
    int sockFd = tcpOpen(SERVER_IP_ADDR, SERVER_PORT_NUM);
    tcpClose(sockFd);
    tcpWrite(sockFd, "This is a test");
    str = tcpRead(sockFd);
    free(str);
    return 0;
}


int tcpOpen(char *  serverName     /* name or IP address of server */,
        int serverPort)
{
    struct sockaddr_in  serverAddr;    /* server's socket address */
    int                 sockAddrSize;  /* size of socket address structure */
    int                 sFd;           /* socket file descriptor */
    int                 n;
    int addr1, addr2, addr3, addr4;
    unsigned int       ipaddr;

    sscanf(serverName, "%d.%d.%d.%d", &addr1, &addr2, &addr3, &addr4);
    ipaddr = ((addr1<<24) & 0xFF000000) |
        ((addr2<<16) & 0x00FF0000) |
        ((addr3<<8)  & 0x0000FF00) |
        (addr4 & 0x000000FF);
    printf("Server: ipaddr[0x%08x], port:[%d]\n", ipaddr, SERVER_PORT_NUM);

    /* create client's socket */
    if ((sFd = socket (AF_INET, SOCK_STREAM, 0)) == ERROR)
    {
        perror ("socket");
        return (ERROR);
    }

    /* bind not required - port number is dynamic */
    /* build server socket address */

    sockAddrSize = sizeof (struct sockaddr_in);
    bzero ((char *) &serverAddr, sockAddrSize);
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = htonl(ipaddr);
    serverAddr.sin_port = htons (SERVER_PORT_NUM);

    /* connect to server */

    if (connect (sFd, (struct sockaddr *) &serverAddr, sockAddrSize) == ERROR)
    {
        printf("connect error!\n");
        close (sFd);
        return (ERROR);
    }
    printf("Connect to Server successfully!\n");
    return sFd;
}


void tcpClose(int fd)
{
    close(fd);
}


void tcpWrite(int fd, const char* cmd)
{
    if (write(fd, cmd, strlen(cmd)) < 0 ||
            (write(fd, "\n", 1) < 0))
    {
        printf("ERROR: tcpWrite() '%s'\n", cmd);
    }
    printf("tcp write successfully!\n");
}

char* tcpRead(int fd)
{
    char *str = malloc(2000);
    char *pos;

    if (read(fd, str, 2000) <= 0)
    {
        printf("ERROR: tcpRead()\n");
    }

    if ((pos = strstr(str, "\n")) != NULL)
    {
        *pos = '\0';
    }
    printf("tcp read: [%s] successfully\n", str);
    return str;
}




你可能感兴趣的:(C/C++)