views:

336

answers:

7

Hi! What's the best way for me to take url like: http://foobar.com/foo.torrent and check if that really is a torrent, not a html page or something else funny. Suggestions? Thank you :)

+1  A: 

Read the torrent file specification, then write a C# app to download the contents of the URL and see if it meets the rules in the specification.

Nate Bross
+3  A: 

Probably best to download and validate it and/ or check the content type is application/x-bittorrent.

Kieron
Note that many web-servers don't serve files with the right content-type. So if the web-servers returns the content-type `"application/octet-stream"` it's still not impossible that the file is a torrent file.
dtb
+4  A: 

The only way to know if it's really a torrent file is to download it and check if it's a torrent file.

dtb
A: 

If you are willing to learn some c++ you could make a external call to the libtorrent library with a P/Invoke I am shure it has a way to validate files.

Scott Chamberlain
+4  A: 

To check the type of a resource without downloading it, use a HEAD request:

WebRequest request= WebRequest.Create("http://foobar.com/foo.torrent");
request.Method= "HEAD";
WebResponse response= request.GetResponse();
if (response.Headers.Get("Content-Type")=="application/x-bittorrent") {
    ...

However, the type application/x-bittorrent might not be set up in some servers, so it's possible you might get application/octet-stream instead, or even text/plain if you are unlucky. If you need to account for this, about all you could do would be to fetch the file with a normal GET request, and see if you can decode it.

The BitTorrent file format is based around a format called ‘bencode’. Here's a .NET library that claims to handle it. You can guess any file that's valid bencode is a torrent file, but if you want to make sure you can look at the mapping it decodes to and check for the info and announce properties.

bobince
nice find and good explanation! +1
tobsen
+1  A: 

In additon to the good answer bobince provided, you could also have a look at the monotorrent open source c# implementation. They download the whole .torrent file and parse the bencode afterwards (cf.: http://anonsvn.mono-project.com/viewvc/trunk/bitsharp/src/MonoTorrent/MonoTorrent.Common/Torrent.cs lines 611ff)

tobsen
+1  A: 

I would use the MonoTorrent library. Specifically, you could use the static method

Torrent.TryLoad(Uri url, string location, out Torrent torrent)

which will return a boolean value indicating whether the url parameter points to a valid torrent file.

Chris Shouts