Welcome to Dream.In.Code
Become a C# Expert!

Join 136,908 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,764 people online right now. Registration is fast and FREE... Join Now!




send and reciving file in c#

 
Reply to this topicStart new topic

send and reciving file in c#

Rating  5
kingmighty_spades
30 Mar, 2008 - 06:56 AM
Post #1

New D.I.C Head
*

Joined: 8 Feb, 2008
Posts: 20


My Contributions
Hi,
I have written a working Send/recivie file program,the problem at hand is this that when a pc has more than 1 local port for example when using (switch,router,modem) .How do I know what Ip to I use for "listening"?

This code will list all local IP's of a PC in a messagebox
CODE


String strHostName = Dns.GetHostName();
// Find host by name
IPHostEntry iphostentry = Dns.GetHostByName(strHostName);
// Grab the first IP addresses
String IPStr = "";
foreach (IPAddress ipaddress in iphostentry.AddressList)
{
IPStr = ipaddress.ToString();
MessageBox.Show(IPStr.ToString());
}




This Code works in the same way as previous only this will only use list first IP and use this IP for listnening when (sending recieving files) How do I know which IP is then right one for listning when there may be several IP's and this Code only considers first IP.


CODE


String GetIP()
{
String strHostName = Dns.GetHostName();
// Find host by name
IPHostEntry iphostentry = Dns.GetHostByName(strHostName);
// Grab the first IP addresses
String IPStr = "";
foreach (IPAddress ipaddress in iphostentry.AddressList)
{
IPStr = ipaddress.ToString();
return IPStr;
}
return IPStr;
}




Would Appreciate any help ty in advance ill be waiting for answer wub.gif
User is offlineProfile CardPM
+Quote Post

kingmighty_spades
RE: Send And Reciving File In C#
30 Mar, 2008 - 09:56 AM
Post #2

New D.I.C Head
*

Joined: 8 Feb, 2008
Posts: 20


My Contributions
plzzzzzzzzzzzzzzzzz help me blink.gif blush.gif blush.gif devil.gif cry2.gif
User is offlineProfile CardPM
+Quote Post

kingmighty_spades
RE: Send And Reciving File In C#
31 Mar, 2008 - 05:37 AM
Post #3

New D.I.C Head
*

Joined: 8 Feb, 2008
Posts: 20


My Contributions
Was something unclear in my last post/question? if you need more info please let me know
User is offlineProfile CardPM
+Quote Post

zakary
RE: Send And Reciving File In C#
31 Mar, 2008 - 06:11 AM
Post #4

D.I.C Regular
Group Icon

Joined: 15 Feb, 2005
Posts: 406



Thanked: 6 times
Dream Kudos: 175
My Contributions
The code you have is fine. Where are you receiving an error.
User is offlineProfile CardPM
+Quote Post

kingmighty_spades
RE: Send And Reciving File In C#
31 Mar, 2008 - 08:13 AM
Post #5

New D.I.C Head
*

Joined: 8 Feb, 2008
Posts: 20


My Contributions
QUOTE(kingmighty_spades @ 31 Mar, 2008 - 06:37 AM) *

Was something unclear in my last post/question? if you need more info please let me know



correct the code works fine BUT when there are several IPs it doesnt choose main IP how do I know which Ip is the main to use for listening
User is offlineProfile CardPM
+Quote Post

zakary
RE: Send And Reciving File In C#
31 Mar, 2008 - 09:07 AM
Post #6

D.I.C Regular
Group Icon

Joined: 15 Feb, 2005
Posts: 406



Thanked: 6 times
Dream Kudos: 175
My Contributions
not sure if there is a way, I have never seen
csharp

/// <summary>
/// returns Local IP address.
/// </summary>
public string LocalIP()
{
string ipAddress = string.Empty;
ipAddress = System.Net.Dns.GetHostName();

// Then using host name, get the IP address list..
System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostByName(ipAddress);
System.Net.IPAddress[] addr = ipEntry.AddressList;
string ip = addr[0];
return ip;
}

not work for any application
User is offlineProfile CardPM
+Quote Post

kingmighty_spades
RE: Send And Reciving File In C#
31 Mar, 2008 - 10:18 AM
Post #7

New D.I.C Head
*

Joined: 8 Feb, 2008
Posts: 20


My Contributions
QUOTE(zakary @ 31 Mar, 2008 - 10:07 AM) *

not sure if there is a way, I have never seen
csharp

/// <summary>
/// returns Local IP address.
/// </summary>
public string LocalIP()
{
string ipAddress = string.Empty;
ipAddress = System.Net.Dns.GetHostName();

// Then using host name, get the IP address list..
System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostByName(ipAddress);
System.Net.IPAddress[] addr = ipEntry.AddressList;
string ip = addr[0];
return ip;
}

not work for any application



when trying to connect to a computer connected through ADSL modem and router it wont work







User is offlineProfile CardPM
+Quote Post

kingmighty_spades
RE: Send And Reciving File In C#
31 Mar, 2008 - 10:39 AM
Post #8

New D.I.C Head
*

Joined: 8 Feb, 2008
Posts: 20


My Contributions
CODE


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace Sserver
{
    public partial class Form1 : Form
    {
        private Socket m_mainSocket;
        public Form1()
        {
            InitializeComponent();
             textBoxIP.Text = GetIP();
            FTServerCode.receivedPath = "";
        }
        String GetIP()
        {
            String strHostName = Dns.GetHostName();

            // Find host by name
            IPHostEntry iphostentry = Dns.GetHostByName(strHostName);

            // Grab the first IP addresses
            String IPStr = "";
            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {
                IPStr = ipaddress.ToString();
                return IPStr;
            }
            return IPStr;
        }

        public void StartListening()
        {
            //try
            //{
            //    // Check the port value
            //    if (textBoxPort.Text == "")
            //    {
            //        MessageBox.Show("Please enter a Port Number");
            //        return;
            //    }
            //    string portStr = textBoxPort.Text;
            //    int port = System.Convert.ToInt32(portStr);

            //    // Create the listening socket...
            //    // tarife socket ke listen ro anjam mide
            //    m_mainSocket = new Socket(AddressFamily.InterNetwork,
            //        SocketType.Stream,
            //        ProtocolType.Tcp);
            //    // tarfie ip va noesh va port
            //    IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
            //    // Bind to local IP Address...
            //    //vasle kardane ip be socket
            //   m_mainSocket.Bind(ipLocal);
            //    // Start listening...
            //    // shoro kardane listen va in 4 yani teddade connectionhayee ke montazeer mimonan
            //    m_mainSocket.Listen(4);

            //}
            //catch (Exception ex)
            //{
            //     MessageBox.Show(ex.Message);
            //}

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            StartListening();
            WebClient client = new WebClient();

            // Add a user agent header in case the requested URI contains a query.
            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR1.0.3705;)");

            string baseurl = "http://www.whatismyip.org/";

            Stream data = client.OpenRead(baseurl);
            StreamReader reader = new StreamReader(data);
            string s = reader.ReadToEnd();
            data.Close();
            reader.Close();
            s = s.Replace("<html><head><title>Current IP Check</title></head><body>", "").Replace("</body></html>", "").ToString();
            textBox1.Text = s;

        }
        class FTServerCode
        {
            IPEndPoint ipEnd;
            Socket sock;
            public FTServerCode()
            {

                ipEnd = new IPEndPoint(IPAddress.Any, 10000);
                sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                sock.Bind(ipEnd);
            }
            public static string receivedPath;
            public static string curMsg = "Stopped";
            public void StartServer()
            {
                try
                {
                    curMsg = "Starting...";
                    sock.Listen(100);

                    curMsg = "Running and waiting to receive file.";
                    Socket clientSock = sock.Accept();

                    byte[] clientData = new byte[1024 * 5000];

                    int receivedBytesLen = clientSock.Receive(clientData);
                    curMsg = "Receiving data...";

                    int fileNameLen = BitConverter.ToInt32(clientData, 0);
                    string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);

                    BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + "/" + fileName, FileMode.Append));;
                    bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);

                    curMsg = "Saving file...";

                    bWrite.Close();
                    clientSock.Close();
                    curMsg = "Reeived & Saved file; Server Stopped.";
                }
               catch
                    //(Exception ex)
                {
                    //curMsg = "File Receving error.";
                    MessageBox.Show("File Receving error.");
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                FTServerCode.receivedPath = fd.SelectedPath;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (FTServerCode.receivedPath.Length > 0)
            {
                backgroundWorker1.RunWorkerAsync();
                button2.Enabled = false;
            }
            else
                MessageBox.Show("Please select file receiving path","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
        }
        FTServerCode obj = new FTServerCode();
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            obj.StartServer();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label5.Text = FTServerCode.receivedPath;
            label3.Text = FTServerCode.curMsg;
        }



    }
}



This Code works in the same way as previous only this will only use list first IP and use this IP for listnening when (sending recieving files) How do I know which IP is then right one for listning when there may be several IP's and this Code only considers first IP.




CODE



        String GetIP()
        {
            String strHostName = Dns.GetHostName();

            // Find host by name
            IPHostEntry iphostentry = Dns.GetHostByName(strHostName);

            // Grab the first IP addresses
            String IPStr = "";
            foreach (IPAddress ipaddress in iphostentry.AddressList)
            {
                IPStr = ipaddress.ToString();
                return IPStr;
            }
            return IPStr;


This post has been edited by kingmighty_spades: 31 Mar, 2008 - 11:06 AM
User is offlineProfile CardPM
+Quote Post

AnarchyRising
RE: Send And Reciving File In C#
8 Apr, 2008 - 09:24 PM
Post #9

New D.I.C Head
*

Joined: 8 Apr, 2008
Posts: 1


My Contributions
QUOTE(kingmighty_spades @ 31 Mar, 2008 - 11:39 AM) *


This Code works in the same way as previous only this will only use list first IP and use this IP for listnening when (sending recieving files) How do I know which IP is then right one for listning when there may be several IP's and this Code only considers first IP.



If you're referring to the machines outside IP, the best (but maybe not the most elegant) way I have found to do it is to make a small class to query either a webservice or site such as whatismyip.com, or develop your own. Have the small class ask the service which will return the true IP address to the machine accessible outside the router.

Other than that, I've been searching google for you for the past half hour and no results yet.
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/3/08 09:53PM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month