Click here to Skip to main content
15,908,674 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to connect the server using IP address and port and transfer the Rig Machine data files to my local machine.

It may be intranet based systems or remote systems. Please help me. I just tried this code, but error as

Exception thrown: 'System.Net.Sockets.SocketException' in System.dll.

when it is reaching the line--socket.bind(ipEnd);


Please help me. Thanks a lot.

What I have tried:

C#
string host; int port= 5040; host = Convert.ToString("192.162.0.47");

//IPAddress[] IPs = Dns.GetHostAddresses(host);
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse(host), 5040);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

sock.Bind(ipEnd);
sock.Listen(100);


Socket clientSock = sock.Accept();

byte[] clientData = new byte[1024 * 5000];
string receivedPath = "Projects/";

int receivedBytesLen = clientSock.Receive(clientData);
int fileNameLen = BitConverter.ToInt32(clientData, 0);
string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
Console.WriteLine("Client:{0} connected & File {1} started received.", clientSock.RemoteEndPoint, fileName);
BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + fileName, FileMode.Append)); ;
bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
Console.WriteLine("File: {0} received & saved at path: {1}", fileName, receivedPath);

bWrite.Close();
clientSock.Close();
Console.ReadLine();
Posted
Updated 11-Jun-20 1:02am
v2
Comments
Greg Utas 11-Jun-20 7:04am    
I have no experience with C#, but with winsock2.h (C/C++) you have to call WSAStartup before doing any network stuff. Is something similar required in C#?

1 solution

You are trying to bind a local socket to a remote address. Then you are listening for a remote connection. This is the wrong way round, the client needs to connect to the server and make a request for whatever data you are trying to receive. See Socket Class (System.Net.Sockets) | Microsoft Docs[^] for a simple example.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900