Sockets between D and C(++) app
FreeSlave
freeslave93 at gmail.com
Wed Apr 2 14:54:56 PDT 2014
It's only server. Maybe problem is on client side.
Try this if you are on Linux:
//Linux C client
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>
int main()
{
int sock, res;
struct sockaddr_in addr;
const char* hello;
size_t len;
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0)
{
printf("Can't create socket\n");
return -1;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(5432);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
hello = "Hello from C";
len = strlen(hello);
while (1)
{
res = sendto(sock, hello, len, 0, (struct
sockaddr*)&addr, sizeof(addr));
if (res <= 0)
{
printf("Can't send\n");
return -1;
}
}
close(sock);
return 0;
}
//D server
import std.socket;
import std.stdio;
int main(string[] args)
{
auto s = new UdpSocket(AddressFamily.INET);
auto addr = new InternetAddress("127.0.0.1", 5432);
s.setOption(SocketOptionLevel.IP, SocketOption.REUSEADDR,
true);
s.bind(addr);
while (true)
{
ubyte[2048] recv_buf;
int count = s.receiveFrom(recv_buf[]);
char[] test = cast(char[])recv_buf;
writefln("Received: %s\n", test);
}
return 0;
}
Note that you don't need to remove zero-symbol if you don't pass
it from client.
More information about the Digitalmars-d-learn
mailing list