1980/01/01(火)ごみ

はてブ数 2011/09/01 23:47 未分類つーさ

#include <stdio.h>
#include <windows.h>

#pragma comment(lib, "wsock32.lib")

int main(int argc, char *argv[])
{
	char buf[1024];
	WSADATA wsadata;
	WSAStartup(0x0002, &wsadata);

	// socket
	SOCKET soc = socket(AF_INET, SOCK_DGRAM, 0);
	printf("socket: %d\\n", soc);

#if 1
	// bind
	sockaddr_in addr;
	addr.sin_family = PF_INET;
	addr.sin_port = htons(59000);
	addr.sin_addr.S_un.S_addr = 0x0200007Fu; // 127.0.0.2
	addr.sin_addr.S_un.S_addr = 0x0300007Fu; // 127.0.0.3
	int ret = bind(soc, (sockaddr*)&addr, sizeof(addr));
	printf("bind: %d\\n", ret);
	if (ret != 0)
		return 1;
#endif

#if 1
	// recv
	printf("waiting...\\n");
	sockaddr_in from;
	int sizeoffrom = sizeof(from);
	int r = recvfrom(soc, buf, sizeof(buf), 0, (sockaddr*)&from, &sizeoffrom);
	printf("recv: %d\\n", r);
#else
	// send
	printf("sending...\\n");
	sockaddr_in to;
	to.sin_family = PF_INET;
	to.sin_port = htons(59000);
	//to.sin_addr.S_un.S_addr = 0x0200007Fu; //unicast
	to.sin_addr.S_un.S_addr = 0xFFFFFF7Fu; //broadcast
	int r = sendto(soc, buf, 16, 0, (sockaddr*)&to, sizeof(to));
	int err = GetLastError();
	printf("send: %d, err = %d\\n", r, err);
	
#endif
	closesocket(soc);
	WSACleanup();
	return 0;
}