Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <winsock2.h>
- #include <ws2tcpip.h>
- #include <stdio.h>
- #pragma comment(lib, "Ws2_32.lib")
- int main() {
- WSDATA wsaData;
- int iResult,
- PORT,
- HOST;
- char *msg = "Hello I'am Client!\n",
- recvbuf[1024];
- struct addrinfo *result = NULL,
- *ptr = NULL,
- Cltsock;
- /*Passing argument */
- if(argc == 3) {
- PORT = argv[2];
- HOST = argv[1];
- msg = argv[3];
- }
- else {
- printf("Usage: %s [HOST] [PORT] [Msg]", argv[0]);
- }
- /* Initialize Winsock*/
- if((iResult = WSAStartup(MAKEWORD(2,2), &wsaData)) != 0) {
- printf("WSAStartup failed: %d\n", iResult);
- return 1;
- }
- /* Passing parameter to struct */
- ZeroMemory(&Cltsock, sizeof(Cltsock));
- Cltsock.ai_family = AF_UNSPEC;
- Cltsock.ai_socktype = SOCK_STREAM;
- Cltsock.ai_protocol = IPPROTO_TCP;
- /* Get address info*/
- if((iResult = getaddrinfo(argv[1], PORT, &Cltsock, &result)) != 0) {
- printf("getaddressinfo failed: %d\n", iResult);
- WSACleanup();
- return 1;
- }
- /*Create Socket*/
- SOCKET ConnectSocket = INVALID_SOCKET;
- if((ConnectSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol)) == INVALID_SOCKET) {
- printf("Error at socket(): %ld\n", WSAGetLastError());
- freeaddrinfo();
- WSACleanup();
- return 1;
- }
- /* Connect to server */
- if((iResult = connect(ConnectSocket, result->ai_addr, (int)result->ai_addrlen)) == SOCKET_ERROR) {
- closesocket(ConnectSocket);
- ConnectSocket = INVALID_SOCKET;
- }
- /* Send an initial buffer */
- if((iResult = send(ConnectSocket, msg, (int)strlen(msg), 0)) == SOCKET_ERROR) {
- printf("send failed: %d\n", WSAGetLastError());
- closesocket(ConnectSocket);
- WSACleanup();
- return 1;
- }
- printf("Bytes sent: %ld\n", iResult);
- /* Shutdown the connection for sending since no more data will be sent */
- if(iResult == SOCKET_ERROR) {
- printf("Shutdown failed: %d\n", WSAGetLastError());
- closesocket(ConnectSocket);
- WSACleanup();
- return 1;
- }
- /* Recv data until the server close the connecion */
- do {
- iResult = recv(ConnectSocket, recvbuf, 1024, 0);
- if(iResult > 0) {
- printf("Bytes received: %d\n", iResult);
- }
- else if(iResult == 0) {
- printf("Connection closed\n");
- }
- else {
- printf("Recv failed: %d\n", WSAGetLastError());
- }
- } while(iResult > 0);
- /*Disconnection*/
- iResult = shutdown(Connection, SD_SEND);
- if(iResult == SOCKET_ERROR) {
- printf("shutdown failed: %d\n", WSAGetLastError());
- closesocket(ConnectSocket);
- WSACleanup();
- return 1;
- }
- closesocket(ConnectSocket);
- WSACleanup();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement