0x00 开头
写代码前,一定要先理清楚实现的逻辑,之后查找是否存在实现逻辑的系统函数。以下为整理的逻辑
1.创建socket设备文件
2.connect连接到指定的服务器
3.write发送信息给服务器
0x01 代码实现
/*************************************************************************
> File Name: client.cpp
> Author: reacher
> Mail:
> Created Time: Mon 28 Aug 2017 05:44:56 PM PDT
************************************************************************/
#include<iostream>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
#define ErrorMsg(msg){\
do{\
printf("%s \n", msg); \
}while(0);\
}
int main(int argc, char* argv[])
{
int execute_status = 0;
int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if(-1 == socket_fd)
{
ErrorMsg("create socket err!");
exit(1);
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(9999);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
execute_status = connect(socket_fd, (sockaddr*)&addr, sizeof(struct sockaddr_in));
if(-1 == execute_status)
{
ErrorMsg("bind err!");
exit(1);
}
char sendBuf[1024];
memset(sendBuf, 0, sizeof(sendBuf));
strcpy(sendBuf, "gua-Server,i'm gua client! hello");
int size_len = strlen(sendBuf);
write(socket_fd,sendBuf,size_len);
return 0;
}