TCP/IP Client Side App in C++


cli.cpp

#include "windows.h"
#include "winsock2.h"
#include "stdio.h"

int main() {
	WSADATA wsaData;
	struct sockaddr_in server;
	SOCKET sock;
	char buf[32];

	// winsock2
	WSAStartup(MAKEWORD(2,0), &wsaData);

	// 
	sock = socket(AF_INET, SOCK_STREAM, 0);

	// 
	server.sin_family = AF_INET;
	server.sin_port = htons(12345);
	server.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");

	// get connection
	connect(sock, (struct sockaddr *)&server, sizeof(server));

	// initialize buffer
	memset(buf, 0, sizeof(buf));
	int n = 0;

	// send and receive
	send(sock, "HELLO", 5, 0);
	memset(buf, 0, sizeof(buf));
	n = recv(sock, buf, sizeof(buf), 0);
	printf("RcvLen=%d, Rcv=%s\n", n, buf);

	// send and receive
	send(sock, "BYE", 3, 0);
	memset(buf, 0, sizeof(buf));
	n = recv(sock, buf, sizeof(buf), 0);
	printf("RcvLen=%d, Rcv=%s\n", n, buf);

	// terminate winsock2
	WSACleanup();
	 
	return 0;
}
Profile
I have technical job experience in enbedded software development and server side infrastructure/application engineering. I'm interested in programming and computer security.
Objective
To write down my technical knowledge in the place where I can access from anywhere. To share my program source code. To train my writing skill.
Link
  • LinkedIn (preparing)

  • Twitter

  • Facebook (preparing)

  • GitHub

  • StackOverFlow (preparing)

Archives