在 C++ 中通过 UDP 发送字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24559909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:45:51  来源:igfitidea点击:

Sending string over UDP in C++

c++socketsudp

提问by Yoda

I would like to send a string: "Jane Doe"to intranet ip 192.168.0.4to port 9000over UDP. I have done this many times via UDP and TCP by Java, but now I have to do it with standard C++ libraries and I can't find any samples only topics where people just can't make it work.

我想通过UDP发送一个字符串:"Jane Doe"到Intranet ip192.168.0.4到端口9000。我已经通过 UDP 和 TCP 通过 Java 多次这样做了,但是现在我必须使用标准的 C++ 库来做到这一点,而且我找不到任何只有人们无法使其工作的主题的示例。

I know that I have to encode "Jane Doe"as array of bytes then just open socket, pack it in datagram and send it.

我知道我必须编码"Jane Doe"为字节数组,然后打开套接字,将其打包成数据报并发送。

C++ is not my first language and this is small part of code I can't figure out, I've chosen UDP because it is always much simpler than TCP.

C++ 不是我的第一语言,这是我无法弄清楚的一小部分代码,我选择了 UDP,因为它总是比 TCP 简单得多。

回答by selbie

Below is some sample Unix code.

下面是一些示例 Unix 代码。

If this is Windows programming:

如果这是 Windows 编程:

  • "sock" should be of type SOCKETinstead of int.
  • Use closesocketinstead of close
  • #include <winsock2.h>instead of all those unix headers
  • “袜子”应该是类型SOCKET而不是int.
  • 使用closesocket代替close
  • #include <winsock2.h>而不是所有这些unix标头


#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <memory.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <errno.h>
#include <stdlib.h>
#include <iostream>


int resolvehelper(const char* hostname, int family, const char* service, sockaddr_storage* pAddr)
{
    int result;
    addrinfo* result_list = NULL;
    addrinfo hints = {};
    hints.ai_family = family;
    hints.ai_socktype = SOCK_DGRAM; // without this flag, getaddrinfo will return 3x the number of addresses (one for each socket type).
    result = getaddrinfo(hostname, service, &hints, &result_list);
    if (result == 0)
    {
        //ASSERT(result_list->ai_addrlen <= sizeof(sockaddr_in));
        memcpy(pAddr, result_list->ai_addr, result_list->ai_addrlen);
        freeaddrinfo(result_list);
    }

    return result;
}


int main()
{
    int result = 0;
    int sock = socket(AF_INET, SOCK_DGRAM, 0);

    char szIP[100];

    sockaddr_in addrListen = {}; // zero-int, sin_port is 0, which picks a random port for bind.
    addrListen.sin_family = AF_INET;
    result = bind(sock, (sockaddr*)&addrListen, sizeof(addrListen));
    if (result == -1)
    {
       int lasterror = errno;
       std::cout << "error: " << lasterror;
       exit(1);
    }


    sockaddr_storage addrDest = {};
    result = resolvehelper("192.168.0.4", AF_INET, "9000", &addrDest);
    if (result != 0)
    {
       int lasterror = errno;
       std::cout << "error: " << lasterror;
       exit(1);
    }

    const char* msg = "Jane Doe";
    size_t msg_length = strlen(msg);

    result = sendto(sock, msg, msg_length, 0, (sockaddr*)&addrDest, sizeof(addrDest));

    std::cout << result << " bytes sent" << std::endl;

    return 0;

}

回答by James Wierzba

This is very easy to do if you are willing to use the boost library.

如果您愿意使用 boost 库,这很容易做到。

Here is the code snippit

这是代码片段

#include "boost/asio.hpp"
using namespace boost::asio;

...

io_service io_service;
ip::udp::socket socket(io_service);
ip::udp::endpoint remote_endpoint;

socket.open(ip::udp::v4());

remote_endpoint = ip::udp::endpoint(ip::address::from_string("192.168.0.4"), 9000);

boost::system::error_code err;
socket.send_to(buffer("Jane Doe", 8), remote_endpoint, 0, err);

socket.close();