首页 > 解决方案 > 一个简单的 IPv6 TCP 客户端有一些问题

问题描述

由于某种原因,当它尝试连接到服务器时,它会不断抛出错误。在这种情况下,服务器是由教授编写的,所以我确信它可以工作,但尽管多次检查并运行各种测试,但我似乎无法让它为我工作。我会说 htons 采用端口 5000 并对其进行更改,我相信它应该这样做,并且由于某种原因,“::1”也在 serverInfo.sin6_addr 中转换为 {0,0,0,0,0,0,256}通过inet_pton()。我相信其中之一可能是问题,但如果我硬编码它似乎并不重要。

// ConsoleApplication1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <WS2tcpip.h>
#include <ws2ipdef.h>

#define RCVBUFSIZ 50

void DisplayFatalErr(char *errMsg);

int main(int argc, char *argv[])
{
    WSADATA wsaData;
    struct sockaddr_in6 serverInfo;

    //verify the args
    if (argc != 4)
    {
        fprintf(stderr, "Not enough entries. Please try again.");
        exit(1);
    }
    else
    {
        char* serverIPaddr = argv[1];
        int serverport = atoi(argv[2]);
        char* msg = argv[3];
        size_t msgLen = sizeof(msg);
        //make word for the sending of the message.
        int iResult = WSAStartup(MAKEWORD(2, 0), &wsaData);
        if (iResult != 0)
        {
            printf("Winsock did not start properly");
            exit(1);
        }
        //create the socket
        int sock = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
        if (sock == INVALID_SOCKET)
        {
            DisplayFatalErr("socket() function failed.");
        }
        else
        {
            printf("Socket connection was successful");
            //getchar();
        }
        serverInfo.sin6_family = AF_INET6;
        serverInfo.sin6_port = htons(serverport);
        inet_pton(AF_INET6, serverIPaddr, &serverInfo.sin6_addr);
        if (connect(sock, (struct sockaddr*) &serverInfo, sizeof(serverInfo)) < 0)
        {
            DisplayFatalErr("connect() function failed.");
        }
        else
        {
            printf("Connection acheived.");
        }
        //send the message
        if (send(sock, msg, msgLen, 0) != msgLen)
        {
            DisplayFatalErr("Send error.");
        }
        else
        {
            printf("Messenge sent.");
        }
        //recieve the message
        int n = 0;
        int len = 0;
        char rcvBuffer[BUFSIZ];
        char* mrcvBuffer = rcvBuffer;
        while ((n = recv(sock, rcvBuffer, RCVBUFSIZ, 0)) > 0)
        {
            mrcvBuffer += n;
            len += n;

            rcvBuffer[len] = '\0';
            printf("Got a message: '%s'\n", rcvBuffer);
        }
        printf("You reached the end \n");
        close(sock);
    }

    exit(0);
}

标签: ctcpipv6

解决方案


推荐阅读