c++ - 向其他 PC 发送以太网 (UDP) 帧

标签 c++ sockets networking udp ethernet

我正在尝试使用 C++ 将 UDP 帧作为客户端-服务器应用程序从我的笔记本电脑发送到另一台 PC。我正在使用 WireShark 监控以太网端口,但我没有看到从我的笔记本电脑发送的任何信息。有人可以帮忙吗?我错过了重要的一步吗?

/*
Simple udp client
*/

#include "stdafx.h"
#define _WINSOCK_DEPRECATED_NO_WARNINGS

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

#pragma comment(lib,"ws2_32.lib") //Winsock Library

#define SERVER "10.222.14.229"
#define BUFLEN 512
#define PORT 8888

int main(void)
{
    struct sockaddr_in si_other;
    int s, slen = sizeof(si_other);
    char buf[BUFLEN];
    char message[BUFLEN];
    char message1[] = "Hello";
    WSADATA wsa;

    //Initialise winsock
    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
    {
        printf("Failed. Error Code : %d", WSAGetLastError());
        exit(EXIT_FAILURE);
    }
    printf("Initialised.\n");

    //create socket
    if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR)
    {
        printf("socket() failed with error code : %d", WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    memset((char *)&si_other, 0, sizeof(si_other));
    si_other.sin_family = AF_INET;
    si_other.sin_port = htons(PORT);
    si_other.sin_addr.S_un.S_addr = inet_addr(SERVER);
    while (1)
    { 
        if (sendto(s, message1, strlen(message1), 0, (struct sockaddr *) &si_other, slen) == SOCKET_ERROR)
        {
            printf("sendto() failed with error code : %d", WSAGetLastError());
            exit(EXIT_FAILURE);
        } 
    memset(buf, '\0', BUFLEN);   
        puts(buf);
    }
    closesocket(s);
    WSACleanup();
    return 0;
}

最佳答案

该代码没有任何问题 - 它在这里运行良好(除了繁忙的循环)。要么:

  • 数据包没有通过线路发送出去,可能是因为没有到 10.222.14.229 的路由(尝试 ping 它),或者
  • WireShark 运行不正常(它能看到来自您笔记本电脑的其他流量吗?- 它可能有过滤器设置或其他东西)

如果您怀疑 WireShark,您可以随时尝试 Microsoft Network Monitor .

关于c++ - 向其他 PC 发送以太网 (UDP) 帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50738673/

相关文章:

c++ - std::vector<Object> 成员 C++ 的总和

c++ - 错误 : iostream: No such file or directory

sockets - 如何在 Dart 中处理套接字断开连接?

c - 在两个套接字之间共享信息

virtio : how does it control the network speed/duplex? 中的 Linux ethtool

c - ANSI C 中的序列化和反序列化问题

java - NIO连接断开时未获取readyKey

c++ - 迭代器(std::map)在 C++ 中是如何工作的?

c++ - 如何使用指定的 gcc 编译 Armadillo 库?

java - Android - 同步线程与onSensorChanged发送udp数据包