How to write to a socket file descriptor without using ``connect()``?

Viewed 176

I'm trying to write through a socket using its descriptor. I have used bind() to bind the socket to the address I want. Whenever I'm using sendto() everything is OK. But whenever I'm using write() (or send()) I'll face Destination address required(errno 89).

What I'm trying to do is to write through the socket using iovec. In this case we don't have any alternative for writev() to get destination address. As I don't want to connect every single time, I was wondering whether I can do it without having to use connect() or accept() syscalls.

Here is the code I wrote:


int sock = 0;
struct sockaddr_in serv_addr; 
char *hello = "chetori to"; 
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) 
{ 
    printf("\n Socket creation error \n"); 
    return -1; 
} 
int opt = 1; 
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) 
{ 
    perror("setsockopt"); 
    exit(EXIT_FAILURE); 
}

string interface_name = "lo";
ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", interface_name.c_str());
if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, reinterpret_cast<void*>(&ifr), sizeof(ifr)) < 0)
    throw exception();  // Imaginary exception

memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;

string interface_address = "127.0.0.1";
if (inet_aton(interface_address.c_str(), &serv_addr.sin_addr) == 0)
    throw exception();  // Imaginary exception

serv_addr.sin_port = htons(PORT);

if (bind(sock, reinterpret_cast<sockaddr*>(&serv_addr), sizeof(serv_addr)) < 0)
    throw exception();  // Imaginary exception
    
char f[1024] = "Hello there";
char sec[1024] = "How are you";
char th[1024] = "I'm fine";
char fh[1024] = "Bye bye";
struct iovec bufs[] = {
    { .iov_base = f, .iov_len = sizeof(f) },
    { .iov_base = sec, .iov_len = sizeof(sec) },
    { .iov_base = th, .iov_len = sizeof(th) },
    { .iov_base = fh, .iov_len = sizeof(fh) },
};
int iovcnt = sizeof(bufs) / sizeof(struct iovec);
writev(sock, bufs, iovcnt);

Note that Interface name and IP address have no problem and are correct.

0 Answers
Related