12 #include <arpa/inet.h> 14 #include <netinet/tcp.h> 15 #include <sys/ioctl.h> 24 #define DB_FLG "[NetWork] " 25 #define PRINT_ERR printf 27 #define PERRNO(ret, db_flg, str) \ 30 PRINT_ERR("%s%s, errno=%d\n", db_flg, str, errno); \ 37 int sockfd =
static_cast<int> (socket(AF_INET, SOCK_STREAM, 0));
43 int keepInterval = 10;
45 struct timeval timeout = { 2, 0 };
48 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (
char *)&on,
sizeof(on));
50 ret = setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, (
char *)&keepAlive,
53 ret = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPIDLE, (
char *)&keepIdle,
56 ret = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPINTVL, (
char *)&keepInterval,
57 sizeof(keepInterval));
59 ret = setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPCNT, (
char *)&keepCount,
62 ret = setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (
char *)&timeout,
63 sizeof(
struct timeval));
67 struct sockaddr_in local_addr;
68 local_addr.sin_family = AF_INET;
69 local_addr.sin_port = htons(port);
70 local_addr.sin_addr.s_addr = inet_addr(local_ip);
71 ret = bind(sockfd, (
struct sockaddr *)&local_addr,
sizeof(local_addr));
74 int ret = listen(sockfd, 10);
81 struct sockaddr_in server_addr;
82 server_addr.sin_family = AF_INET;
83 server_addr.sin_port = htons(server_port);
84 inet_aton(server_ip, &server_addr.sin_addr);
86 connect(*socket, (
struct sockaddr *)&server_addr,
sizeof(server_addr));
92 int ret = send(client_fp, (
void *)data, len, 0);
int socket_connect_server(int *socket, char server_ip[], int server_port)
#define PERRNO(ret, db_flg, str)
int socket_init(char *local_ip, int port, int is_server)
int socket_send_data(int client_fp, unsigned char *data, int len)