我有一个C脚本,它连接到带有套接字的远程服务器并写入命令。
我必须尽快做到这一点,我需要从源ip addressess切换。问题是,当我从ip地址切换时,绑定会慢下来几秒钟。
我找不到解决方案。
代码:
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
int main()
{
struct sockaddr_in source, destination = {}; //two sockets declared as previously
int sock = 0;
int n = 0;
int datalen = 0;
int pkt = 0;
char* ips[3] = {"10.0.0.1", "10.0.0.2", "10.0.0.3"};
uint8_t *send_buffer;
char recv_buffer[11];
struct sockaddr_storage fromAddr; // same as the previous entity struct sockaddr_storage serverStorage;
unsigned int addrlen; //in the previous example socklen_t addr_size;
struct timeval tv;
tv.tv_sec = 3; /* 3 Seconds Time-out */
tv.tv_usec = 0;
/*Inititalize source to zero*/
memset(&source, 0, sizeof(source)); //source is an instance of sockaddr_in. Initialization to zero
/*Inititalize destinaton to zero*/
memset(&destination, 0, sizeof(destination));
/* setting the destination, i.e our OWN IP ADDRESS AND PORT */
destination.sin_family = AF_INET;
// destination.sin_addr.s_addr = inet_addr("123.456.789.123");
destination.sin_port = htons(43);
/*---- Configure settings of the source address struct, WHERE THE PACKET IS COMING FROM ----*/
/* Address family = Internet */
source.sin_family = AF_INET;
/* Set IP address to localhost */
// source.sin_addr.s_addr = INADDR_ANY;
/* Set port number, using htons function to use proper byte order */
source.sin_port = htons(43);
/* Set all bits of the padding field to 0 */
memset(source.sin_zero, '\0', sizeof source.sin_zero); //optional
int i;
for (i=0; i<60; i++) {
/* creating the socket */
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
printf("Failed to create socket\n");
/*set the socket options*/
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval));
if(inet_pton(AF_INET, ips[i%3], &source.sin_addr)<=0) //this is where is switch the ip addresses
{
printf("\n inet_pton error occured\n");
return 1;
}
/*bind socket to the source WHERE THE PACKET IS COMING FROM*/
if (bind(sock, (struct sockaddr *) &source, sizeof(source)) < 0)
printf("Failed to bind socket");
if(inet_pton(AF_INET, "94.198.154.139", &destination.sin_addr)<=0)
{
printf("\n inet_pton error occured\n");
return 1;
}
if(connect(sock, (struct sockaddr *)&destination, sizeof(destination)) < 0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
printf("check\n");
n = write(sock,"is liveresults.nl\r\n",21);
if (n < 0) error("ERROR writing to socket");
while ( (n = read(sock, recv_buffer, sizeof(recv_buffer)-1)) > 0)
{
recv_buffer[n] = 0;
if(fputs(recv_buffer, stdout) == EOF)
{
printf("\n Error : Fputs error\n");
}
}
if(n < 0)
{
printf("\n Read error \n");
}
close(sock);
}
return 0;
}
编辑:我必须注意到每个ip的第一个循环都会减慢速度。因为我有3个IP地址。在第一轮之后,每个绑定会减慢几秒钟。
答案 0 :(得分:0)
我必须将本地端口绑定到0而不是与传出端口相同的端口。