gpt4 book ai didi

Java 套接字到 C 套接字

转载 作者:行者123 更新时间:2023-11-30 04:03:40 24 4
gpt4 key购买 nike

谁能帮我把这段Java代码翻译成C语言。我尝试了很多不同的方法,但没有成功。我在缓冲区部分遇到问题,我不知道如何存储数据然后使用 C 套接字发送它。

SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 6633));

ByteBuffer buf = ByteBuffer.allocate(48);
buf.clear();

byte version = 0x01;
short length = 8;
byte type = 0;

buf.put(version);
buf.put(type);
buf.putShort(length);
buf.putInt(12356);

buf.flip();
socketChannel.write(buf);

谢谢。

最佳答案

下面是代码:

SOCKET sock = socket(PF_INET, SOCK_STREAM, 0);
struct sockaddr_in thataddr;
thataddr.sin_addr.s_addr = inet_addr("127.0.0.1");
thataddr.sin_family = AF_INET;
thataddr.sin_port = htons(6633);
connect(sock, (LPSOCKADDR) &thataddr, sizeof(thataddr));
typedef struct SendThis
{
unsigned char version;
unsigned int length;
unsigned char type;
};
SendThis sendThis;
sendThis.version = '1';
sendThis.length = 8;
sendThis.type = 0;
send(sock,(char *)&sendThis,sizeof(SendThis),0);

它未经测试,还可以在需要的地方添加错误检查。

关于Java 套接字到 C 套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21322537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com