【问题标题】:Connecting to a device in LAN over TCP/IP using C使用 C 通过 TCP/IP 连接到 LAN 中的设备
【发布时间】:2016-11-06 08:32:43
【问题描述】:

我正在尝试使用 C 连接到驻留在 LAN 中的设备(Allen-Bradley PLC)。 我尝试连接的设备没有托管侦听我的应用程序的应用程序(因为我无法控制它)。 建立连接后,我可以发送和接收请求数据的数据包。我已经用 C#(使用 System.Net.Sockets)开发了一个可以与该设备连接并通信的工作应用程序。 但是,我正在编写的 C 代码似乎在建立连接的部分失败了。 这是我的源代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifdef WINDOWS
#include <winsock2.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

#include <errno.h>


int main() {
char *servIP = "192.168.10.31";

in_port_t servPort = 503;

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

if (sock < 0) {
    fprintf(stderr, "socket() failed: %s\n", strerror(errno));
    exit(1);
}

struct sockaddr_in servAddr;
memset(&servAddr, 0, sizeof(servAddr));

servAddr.sin_family = AF_INET;

int rtnVal = inet_pton(AF_INET, servIP, &servAddr.sin_addr.s_addr);
if (rtnVal <= 0)
{
    printf("failed"); exit(1);
}

if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
{
    printf("failed connecting"); exit(1);
}
else {
    printf("connected");
}

char x[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
printf("terE");
write(sock, x, sizeof(x));

char buffer[1024];
recv(sock, buffer, 1024, 0);
printf("Data received: %s", buffer);


}

【问题讨论】:

  • 似乎在建立连接的部分失败了。什么错误?请详细说明一下好吗?
  • 旁注:你确定 buffer 是一个空终止的 C 字符串吗?
  • @LPs 程序在“连接失败”部分退出。缓冲区只是一个意大利面条代码,用于测试连接是否首先建立,

标签: c sockets tcp plc


【解决方案1】:

您忘记将调用的端口设置为connect()

您定义了一个servPort 变量,但您没有将它分配给servAddr 变量。

所以你应该添加:

servAddr.sin_port = htons(servPort);

或者简单地说:

servAddr.sin_port = htons(503);

【讨论】:

    【解决方案2】:

    你忘记了你的代码的 sin_port。

    而且您还忘记了 WSAStartup。看看这个教程可能会有所帮助:

    http://www.tenouk.com/Winsock/Winsock2example.html

    【讨论】:

    • s_addr 由在connect() 之前的inet_pton() 调用填充。但是你在 Windows 上需要 WSAStartup() 是对的。
    猜你喜欢
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    相关资源
    最近更新 更多