Reputation: 11
Can any one help me translate this Java code to C. I have tried so many different ways but with no success. I have the problem in the buffer part I don't know how to store the data and then send it using a C socket.
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);
Thanks.
Upvotes: 1
Views: 192
Reputation: 151
Below is the code:
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);
Its not tested, also add error checks, wherever it is required.
Upvotes: 2