/* Internet address. */
struct in_addr {
__u32 s_addr;
};
/* Structure describing an Internet (IP) socket address. */
#define __SOCK_SIZE__ 16 /* sizeof(struct sockaddr) */
struct sockaddr_in {
sa_family_t sin_family; /* Address family */
unsigned short int sin_port; /* Port number */
struct in_addr sin_addr; /* Internet address */
/* Pad to size of `struct sockaddr'. */
unsigned char __pad[__SOCK_SIZE__ - sizeof(short int) -
sizeof(unsigned short int) - sizeof(struct in_addr)];
};
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define RECV_BUF_SIZE 1024
int main(int argc, char **argv)
{
int sockfd = 0;
int ret = 0;
char recvbBuffer[RECV_BUF_SIZE] = {0};
struct sockaddr_in serverAddr;
memset(&serverAddr, 0, sizeof(struct sockaddr_in));
if (argc != 3)
{
fprintf(stderr, "Usage: %s host port msg...\n", argv[0]);
exit(EXIT_FAILURE);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
fprintf(stderr, "Create socket fail\n");
exit(EXIT_FAILURE);
}
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(atoi(argv[2]));
ret = inet_aton(argv[1], (struct in_addr *)(&serverAddr.sin_addr.s_addr));
if (0 == ret)
{
fprintf(stderr, "Server address %s error\n", argv[1]);
exit(EXIT_FAILURE);
}
ret = connect(sockfd, (struct sockaddr *)(&serverAddr), sizeof(serverAddr));
if (ret != 0)
{
fprintf(stderr, "Connect server %s:%d fail\n", argv[1], atoi(argv[2]));
exit(EXIT_FAILURE);
}
recv(sockfd, recvbBuffer, RECV_BUF_SIZE, 0);
printf("%s", recvbBuffer);
close(sockfd);
return 0;
}
root@ubuntu:~/network_program/simple_client# ./a.out 127.0.0.1 21
220 (vsFTPd 2.2.2)
root@ubuntu:~/network_program/simple_client# ./a.out 127.0.0.1 22
SSH-2.0-OpenSSH_5.3p1 Debian-3ubuntu7
root@ubuntu:~/network_program/simple_client# ./a.out 127.0.0.1 23
Connect server 127.0.0.1:23 fail