我如何收到Winsock的UDP数据包在C ++?(How do I receive udp pac

2019-08-16 16:57发布

截至包裹我的头周围UDP套接字的尝试我试图移植代码本教程页面http://www.linuxhowtos.org/C_C++/socket.htm到的Winsock(在Win 8上运行,如果它事项)。 [下面直接链接]

在目前的代码编译和运行,但我从来没有收到一个数据包,这两个程序就等着和recvfrom的块()。 我一直有这个代码的修改版本同样的问题(例如https://stackoverflow.com/a/679529/873217包括recvfrom的()调用,而与此代码C ++问题数据报(UDP)WINSOCKET到SENDTO和recvfrom通过环回适配器在同一插座上进行更改的建议)。 我想我在做一些简单和基本的错误; 但我无法找到它在我自己的。 希望更有经验的人可以照一些轻就这个问题对我来说。 谢谢。

补充说明:
我运行的exe文件服务器,然后在同一台计算机上的客户端EXE。 它连接到互联网。 我已经使用解析为我的IP地址和域名尝试。 我也曾尝试禁用防火墙,尽管我已批准这两个方案完全访问权限。

直接链接到原始客户端和服务器端的代码:
http://www.linuxhowtos.org/data/6/client_udp.c
http://www.linuxhowtos.org/data/6/server_udp.c

我目前的尝试:

首尾相连libws2_32.a

客户代码:

#include <stdio.h>
#include <winsock2.h>
#include <string.h>

void error(const char *);

int main()
{
    WSAData data;
    WSAStartup( MAKEWORD( 2, 2 ), &data );

    int sock, n;
    int length;
    struct sockaddr_in server, from;
    struct hostent *hp;
    char buffer[256];
    unsigned short serverPort = 27072;
    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) error("socket");
    server.sin_family = AF_INET;
    hp = gethostbyname("localhost");//have also tried my url
    if (hp==0) error("Unknown host");
    memmove((char *)hp->h_addr, (char *)&server.sin_addr, hp->h_length);
    server.sin_port = htons(serverPort);
    length = sizeof(struct sockaddr_in);
    printf("Please enter the message: ");
    memset(buffer, 0, 256);
    fgets(buffer, 255, stdin);
    n = sendto (sock, buffer, strlen(buffer), 0, (const struct sockaddr *)&server, length);
    if (n < 0) error("Sendto");
    printf("sent %i bytes\n", n);
    n = recvfrom(sock, buffer, 256, 0, (struct sockaddr *)&server, &length);
    if (n < 0) error("recvfrom");
    //write(1,"Got an ack: ", 12);
    //write(1, buffer, n);
    printf("Got msg: %s\n",buffer);

    closesocket(sock);
    WSACleanup();
    return(0);
}

void error(const char *msg)
{
    perror(msg);
    exit(0);
}

服务器代码:

#include <stdio.h>
#include <winsock2.h>
#include <string.h>

void error(const char *);

int main()
{
    WSAData data;
    WSAStartup( MAKEWORD( 2, 2 ), &data );

    int sock, length, n;
    int fromlen;
    struct sockaddr_in server;
    struct sockaddr_in from;
    char buf[1024];
    unsigned short serverPort = 27072;
    sock=socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) error("Opening socket");
    length = sizeof(server);
    memset(&server, 0, length);
    server.sin_family = AF_INET;
    server.sin_addr.s_addr=INADDR_ANY;
    server.sin_port=htons(serverPort);
    if (bind(sock,(struct sockaddr *)&server, length)<0) error ("binding");
    fromlen = sizeof(struct sockaddr_in);
    while(1)
    {
        n = recvfrom(sock, buf, 1024, 0, (struct sockaddr *)&from, &fromlen);
        if (n<0) error("recvfrom");
        //write(1,"Received a datagram: ", 21);
        //write(1,buf,n);
        printf("Received a datagram: %s", buf);
        n = sendto(sock, "Got your message\n",17,0,(struct sockaddr *)&from,fromlen);
        if (n<0)error("sendto");
    }
    closesocket(sock);
    WSACleanup();
    return 0;
}


void error (const char *msg)
{
    perror(msg);
    exit(0);
}

Answer 1:

下面UDP测试应用程序正常工作在我的设置 - Windows 7中,VS 2013。

我创造了一些轻量包装类做资源管理,并打开错误代码为例外。 这使得客户端和服务器端的代码更易于阅读。 请务必先运行服务器。

Network.h

#include <WinSock2.h>
#include <WS2tcpip.h>
#include <system_error>
#include <string>
#include <iostream>

#pragma once

class WSASession
{
public:
    WSASession()
    {
        int ret = WSAStartup(MAKEWORD(2, 2), &data);
        if (ret != 0)
            throw std::system_error(WSAGetLastError(), std::system_category(), "WSAStartup Failed");
    }
    ~WSASession()
    {
        WSACleanup();
    }
private:
    WSAData data;
};

class UDPSocket
{
public:
    UDPSocket()
    {
        sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        if (sock == INVALID_SOCKET)
            throw std::system_error(WSAGetLastError(), std::system_category(), "Error opening socket");
    }
    ~UDPSocket()
    {
        closesocket(sock);
    }

    void SendTo(const std::string& address, unsigned short port, const char* buffer, int len, int flags = 0)
    {
        sockaddr_in add;
        add.sin_family = AF_INET;
        add.sin_addr.s_addr = inet_addr(address.c_str());
        add.sin_port = htons(port);
        int ret = sendto(sock, buffer, len, flags, reinterpret_cast<SOCKADDR *>(&add), sizeof(add));
        if (ret < 0)
            throw std::system_error(WSAGetLastError(), std::system_category(), "sendto failed");
    }
    void SendTo(sockaddr_in& address, const char* buffer, int len, int flags = 0)
    {
        int ret = sendto(sock, buffer, len, flags, reinterpret_cast<SOCKADDR *>(&address), sizeof(address));
        if (ret < 0)
            throw std::system_error(WSAGetLastError(), std::system_category(), "sendto failed");
    }
    sockaddr_in RecvFrom(char* buffer, int len, int flags = 0)
    {
        sockaddr_in from;
        int size = sizeof(from);
        int ret = recvfrom(sock, buffer, len, flags, reinterpret_cast<SOCKADDR *>(&from), &size);
        if (ret < 0)
            throw std::system_error(WSAGetLastError(), std::system_category(), "recvfrom failed");

        // make the buffer zero terminated
        buffer[ret] = 0;
        return from;
    }
    void Bind(unsigned short port)
    {
        sockaddr_in add;
        add.sin_family = AF_INET;
        add.sin_addr.s_addr = htonl(INADDR_ANY);
        add.sin_port = htons(port);

        int ret = bind(sock, reinterpret_cast<SOCKADDR *>(&add), sizeof(add));
        if (ret < 0)
            throw std::system_error(WSAGetLastError(), std::system_category(), "Bind failed");
    }

private:
    SOCKET sock;
};

服务器

#include "Network.h"

int main()
{
    try
    {
        WSASession Session;
        UDPSocket Socket;
        char buffer[100];

        Socket.Bind(100);
        while (1)
        {
            sockaddr_in add = Socket.RecvFrom(buffer, sizeof(buffer));

            std::string input(buffer);
            std::reverse(std::begin(input), std::end(input));
            Socket.SendTo(add, input.c_str(), input.size());
        }
    }
    catch (std::system_error& e)
    {
        std::cout << e.what();
    }
}

客户

#include "Network.h"

int main()
{
    try
    {
        WSASession Session;
        UDPSocket Socket;
        std::string data = "hello world";
        char buffer[100];

        Socket.SendTo("127.0.0.1", 100, data.c_str(), data.size());
        Socket.RecvFrom(buffer, 100);
        std::cout << buffer;
    }
    catch (std::exception &ex)
    {
        std::cout << ex.what();
    }
    char c;
    std::cin >> c;
}


Answer 2:

嗯,我不知道,如果winsock2.h工作在Windows和Linux以同样的方式,但是,在Windows中,当您创建套接字,您必须设置您所使用的协议,TCP或UDP:

SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

AF_INET = IPv4的; SOCK_STREAM =用于TCP字节流; IPPROTO_TCP = TCP协议。

对于UDP(这是我以前从未使用过),根据MSDN这将是:

SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

SOCK_DGRAM为UDP =字节流; IPPROTO_UDP = UDP协议。

该代码将在Windows工作。 我想对Linux来说是相似的。



文章来源: How do I receive udp packets with winsock in c++?